Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/main/NEMO_coding_conv.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/main/NEMO_coding_conv.tex	(revision 11352)
+++ 	(revision )
@@ -1,807 +1,0 @@
-\documentclass{article}
-
-\usepackage{fancyhdr}
-\usepackage{times}
-\usepackage{graphicx}
-\usepackage{hyperref}
-\usepackage{minted}
-%\usepackage[normalem]{ulem}   % striketrough style with \sout{...}
-
-\hypersetup{pdftitle={NEMO coding conventions}, pdfauthor={NEMO System Team}, colorlinks}
-\setminted{style=emacs, breaklines, frame=leftline}
-\newmintinline[forcode]{fortran}{fontsize=auto, frame=lines}   % \forcode{...}
-\newminted[forlines]{fortran}{}                                % \begin{forlines}
-
-\pagestyle{empty}
-\setlength{\leftmargin}{1 cm}
-\setlength{\rightmargin}{1 cm}
-\setlength{\oddsidemargin}{0 cm}
-\setlength{\evensidemargin}{0 cm}
-\setlength{\topmargin}{-1cm}
-\setlength{\textwidth}{16 cm}
-\setlength{\textheight}{25cm}
-\pagestyle{fancy}
-
-\title{
-  \includegraphics[width=0.3\textwidth]{../../../figures/NEMO_grey} \\
-  \vspace{1.0cm} \rule{345pt}{1.5pt} \\
-  \vspace{0.45cm} {\Huge NEMO coding conventions} \rule{345pt}{1.5pt} \\
-}
-%\title{NEMO coding conventions}
-\author{\Large NEMO System Team
-  \thanks{
-    To be completed
-  }
-}
-\date{version X.X -- month year}
-
-\begin{document}
-
-\maketitle
-
-\newpage
-
-\tableofcontents
-
-\newpage
-
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-\section{Introduction}
-
-This document describes conventions\index{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\index{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\index{module} 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\index{variable} 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 FORTRAN 95 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} \par & & & & \\
-      \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 hardwired 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\index{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 inlined (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 subdomains 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
-  Labeled \forcode{DO} construct
-  (use unlabeled \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 subprogram 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}
-
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-
-% \printindex
-% \input NEMO_coding.conv.ind
-
-\end{document}
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/main/appendices.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/main/appendices.tex	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/main/appendices.tex	(revision 11353)
@@ -4,5 +4,5 @@
 \subfile{../subfiles/annex_C}             %% Discrete invariants of the eqs.
 \subfile{../subfiles/annex_iso}	          %% Isoneutral diffusion using triads
-\subfile{../subfiles/annex_D}             %% Coding rules
+\subfile{../subfiles/annex_DOMAINcfg}     %% Brief notes on DOMAINcfg
 
 %% Not included
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/main/bibliography.bib
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/main/bibliography.bib	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/main/bibliography.bib	(revision 11353)
@@ -188,4 +188,18 @@
 }
 
+@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
@@ -386,4 +400,18 @@
 }
 
+@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
@@ -745,4 +773,18 @@
 }
 
+@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
@@ -819,4 +861,17 @@
 }
 
+@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
@@ -871,4 +926,18 @@
   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"
 }
 
@@ -1839,4 +1908,28 @@
   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"
 }
 
@@ -2306,4 +2399,20 @@
 }
 
+@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",
@@ -2544,4 +2653,18 @@
 }
 
+@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
@@ -2896,4 +3019,15 @@
 }
 
+@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
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/annex_A.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/annex_A.tex	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/annex_A.tex	(revision 11353)
@@ -10,4 +10,15 @@
 
 \minitoc
+
+\vfill
+\begin{figure}[b]
+\subsubsection*{Changes record}
+\begin{tabular}{l||l|m{0.65\linewidth}}
+    Release   & Author        & Modifications \\
+    {\em 4.0} & {\em Mike Bell} & {\em review}  \\
+    {\em 3.x} & {\em Gurvan Madec} & {\em original}  \\
+\end{tabular}
+\end{figure}
+
 
 \newpage
@@ -29,38 +40,85 @@
 \begin{equation}
   \label{apdx:A_s_slope}
-  \sigma_1 =\frac{1}{e_1 }\;\left. {\frac{\partial z}{\partial i}} \right|_s
+  \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 chain rule to establish the model equations in the curvilinear $s-$coordinate system is:
+  \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{apdx:A_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{apdx:A_s_chain_rule}
+      \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{apdx:A_s_slope}), by applying the second of (\autoref{apdx:A_s_infin_changes}) with $\bullet$ set to 
+$s$ and $j, t$ held constant
+\begin{equation}
+\label{apdx:a_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{apdx:A_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{apdx:a_ds_di_z}
+\end{equation}
+Another identity, similar in form to (\autoref{apdx:a_ds_di_z}), can be derived
+by choosing $\bullet$ to be $s$ and using the second form of (\autoref{apdx:A_s_infin_changes}) to consider
+changes in which $i , j$ and $s$ are constant. This shows that
+\begin{equation}
+\label{apdx:A_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{apdx:A_s_chain_rule}
   \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 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} \\
+    +\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}
+    \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}
 
-In particular applying the time derivative chain rule to $z$ provides the expression for $w_s$,
-the vertical velocity of the $s-$surfaces referenced to a fix z-coordinate:
-\begin{equation}
-  \label{apdx:A_w_in_s}
-  w_s   =  \left.   \frac{\partial z }{\partial t}   \right|_s
-  = \frac{\partial z}{\partial s} \; \frac{\partial s}{\partial t}
-  = e_3 \, \frac{\partial s}{\partial t}
-\end{equation}
 
 % ================================================================
@@ -131,43 +189,42 @@
 \end{subequations}
 
-Here, $w$ is the vertical velocity relative to the $z-$coordinate system.
-Introducing the dia-surface velocity component,
-$\omega $, defined as the volume flux across the moving $s$-surfaces per unit horizontal area:
+Here, $w$ is the vertical velocity relative to the $z-$coordinate system. 
+Using the first form of (\autoref{apdx:A_s_infin_changes}) 
+and the definitions (\autoref{apdx:A_s_slope}) and (\autoref{apdx:A_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{apdx:A_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{apdx:A_w_s}
-  \omega  = w - w_s - \sigma_1 \,u - \sigma_2 \,v    \\
-\end{equation}
-with $w_s$ given by \autoref{apdx:A_w_in_s},
-we obtain the expression for the divergence of the velocity 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 \,e_3 }    \left[
+  \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{apdx:A_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 } \frac{\partial w_s       }{\partial s} \\ \\
-      &= \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 } \frac{\partial}{\partial s}  \left(  e_3 \; \frac{\partial s}{\partial t}   \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 \omega }{\partial s}
-        + \frac{\partial}{\partial s} \frac{\partial s}{\partial t}
-        + \frac{1}{e_3 } \frac{\partial s}{\partial t} \frac{\partial e_3}{\partial s} \\ \\
-      &= \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 } \frac{\partial e_3}{\partial t}
-    \end{array}
-        }
-  \end{align*}
-\end{subequations}
+        + \frac{1}{e_3 } \left. \frac{\partial e_3}{\partial t} \right|_s .
+\end{equation}
 
 As a result, the continuity equation \autoref{eq:PE_continuity} in the $s-$coordinates is:
@@ -178,7 +235,7 @@
     {\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}
-A additional term has appeared that take into account
+  +\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.
 
@@ -210,6 +267,5 @@
         + w \;\frac{\partial u}{\partial z} \\ \\
       &= \left. {\frac{\partial u }{\partial t}} \right|_z
-        - \left. \zeta \right|_z v
-        +  \frac{1}{e_1 \,e_2 }\left[ { \left.{ \frac{\partial (e_2 \,v)}{\partial i} }\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
@@ -230,13 +286,13 @@
         } \\ \\
       &= \left. {\frac{\partial u }{\partial t}} \right|_z
-        + \left. \zeta \right|_s \;v
+        - \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}
+        + \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
+        - \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
@@ -245,15 +301,15 @@
         - \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
+        - \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}   \\
+        \; \frac{\partial u}{\partial s} .  \\
         %
-      \intertext{Introducing $\omega$, the dia-a-surface velocity given by (\autoref{apdx:A_w_s}) }
+      \intertext{Introducing $\omega$, the dia-s-surface velocity given by (\autoref{apdx:A_w_s}) }
       %
       &= \left. {\frac{\partial u }{\partial t}} \right|_z
-        + \left. \zeta \right|_s \;v
+        - \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}   \\
+        + \frac{1}{e_3 } \left( \omega + w_s \right) \frac{\partial u}{\partial s}   \\
     \end{array}
     }
@@ -266,11 +322,11 @@
   {
     \begin{array}{*{20}l}
-      w_s  \;\frac{\partial u}{\partial s}
-      = \frac{\partial s}{\partial t} \;  \frac{\partial u }{\partial s}
-      = \left. {\frac{\partial u }{\partial t}} \right|_s  - \left. {\frac{\partial u }{\partial t}} \right|_z \quad ,
+      \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}
   }
 \]
-leads to the $s-$coordinate formulation of the total $z-$coordinate time derivative,
+This leads to the $s-$coordinate formulation of the total $z-$coordinate time derivative,
 \ie the total $s-$coordinate time derivative :
 \begin{align}
@@ -278,7 +334,7 @@
   \left. \frac{D u}{D t} \right|_s
   = \left. {\frac{\partial u }{\partial t}} \right|_s
-  + \left. \zeta \right|_s \;v
+  - \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}
+  + \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
@@ -306,5 +362,5 @@
                                          + \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) \\
+                                         -u	\;\frac{\partial e_1 }{\partial j} 	\right) . \\
   \end{array}
   }
@@ -328,5 +384,5 @@
        -  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{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) \\ \\
@@ -337,7 +393,7 @@
     && - \,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{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)                  \\
+       -u   \;\frac{\partial e_1 }{\partial j} 	\right)     .             \\
      %
     \intertext {Introducing a more compact form for the divergence of the momentum fluxes,
@@ -361,5 +417,5 @@
   + \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)
+    -u  \;\frac{\partial e_1 }{\partial j}            \right).
 \end{flalign}
 which is the total time derivative expressed in the curvilinear $s-$coordinate system.
@@ -377,9 +433,9 @@
     & =-\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
+    &=-\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{apdx:A_s_slope}, it comes:
+replacing $\sigma_1$ and $\sigma_2$ by their expression \autoref{apdx:A_s_slope}, it becomes:
 \begin{equation}
   \label{apdx:A_grad_p_1}
@@ -391,5 +447,5 @@
     -\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) \\
+      + g\;\rho \;\left. {\frac{\partial z}{\partial j}} \right|_s   \right) . \\
   \end{split}
 \end{equation}
@@ -405,6 +461,6 @@
 \[
   \begin{split}
-    p &= g\; \int_z^\eta \rho \; e_3 \; dk = g\; \int_z^\eta \left(  \rho_o \, d + 1 \right) \; e_3 \; dk   \\
-    &= g \, \rho_o \; \int_z^\eta d \; e_3 \; dk + g \, \int_z^\eta e_3 \; dk
+    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}
 \]
@@ -412,13 +468,13 @@
 \begin{equation}
   \label{apdx:A_pressure}
-  p = \rho_o \; p_h' + g \, ( z + \eta )
+  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
+  \frac{\partial p_h'}{\partial k} = - d \, g \, e_3 .
 \]
 
 Substituing \autoref{apdx:A_pressure} in \autoref{apdx:A_grad_p_1} and
-using the definition of the density anomaly it comes the expression in two parts:
+using the definition of the density anomaly it becomes an expression in two parts:
 \begin{equation}
   \label{apdx:A_grad_p_2}
@@ -426,9 +482,9 @@
     -\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} \\
+      + 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}\\
+      + g\; d \;\left. {\frac{\partial z}{\partial j}} \right|_s   \right)  - \frac{g}{e_2 } \frac{\partial \eta}{\partial j} . \\
   \end{split}
 \end{equation}
@@ -463,5 +519,5 @@
     -   \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}}
+    +   D_u^{\vect{U}}  +   F_u^{\vect{U}} ,
   \end{multline}
   \begin{multline}
@@ -473,5 +529,5 @@
     -   \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}}
+    +  D_v^{\vect{U}}  +   F_v^{\vect{U}} .
   \end{multline}
 \end{subequations}
@@ -483,10 +539,10 @@
     \label{apdx:A_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)
+    - \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}}
+    +   D_u^{\vect{U}}  +   F_u^{\vect{U}} ,
   \end{multline}
   \begin{multline}
@@ -494,9 +550,9 @@
     \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}
+    -   \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}}
+    +  D_v^{\vect{U}}  +   F_v^{\vect{U}} . 
   \end{multline}
 \end{subequations}
@@ -505,5 +561,5 @@
 \begin{equation}
   \label{apdx:A_dyn_zph}
-  \frac{\partial p_h'}{\partial k} = - d \, g \, e_3
+  \frac{\partial p_h'}{\partial k} = - d \, g \, e_3 .
 \end{equation}
 
@@ -531,9 +587,9 @@
   \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)
+  -  \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 (A.4),
+The expression for the advection term is a straight consequence of (\autoref{apdx:A_sco_Continuity}),
 the expression of the 3D divergence in the $s-$coordinates established above. 
 
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/annex_B.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/annex_B.tex	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/annex_B.tex	(revision 11353)
@@ -53,14 +53,19 @@
   {
   \begin{array}{*{20}l}
-    D^T=& \frac{1}{e_1\,e_2\,e_3 }\;\left[ {\ \ \ \ e_2\,e_3\,A^{lT} \;\left.
-          {\frac{\partial }{\partial i}\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|_s } \right.  \\
-        &\qquad \quad \ \ \ +e_1\,e_3\,A^{lT} \;\left. {\frac{\partial }{\partial j}\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|_s \\
-        &\qquad \quad \ \ \ + e_1\,e_2\,A^{lT} \;\frac{\partial }{\partial s}\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 } \right.
-          \left. {\left. {+\left( {\varepsilon +\sigma_1^2+\sigma_2 ^2} \right)\;\frac{1}{e_3 }\;\frac{\partial T}{\partial s}} \right)\;\;} \right]
+    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*}
 
-Equation \autoref{apdx:B2} is obtained from \autoref{apdx:B1} without any additional assumption.
+\autoref{apdx:B2} is obtained from \autoref{apdx:B1} 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:A} and
@@ -90,14 +95,14 @@
   {
   \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}$, it becomes:}
+    \intertext{Noting that $\frac{1}{e_1} \left. \frac{\partial e_3 }{\partial i} \right|_s = \frac{\partial \sigma_1 }{\partial s}$, this becomes:}
     %
-    & =\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. \\
+    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 z}} \right)\;\;\;} \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]}
+    & \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}
       } \\
@@ -105,10 +110,10 @@
   \begin{array}{*{20}l}
     %
-    \intertext{using the same remark as just above, it becomes:}
+    \intertext{Using the same remark as just above, $D^T$ becomes:}
     %
-    &= \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.\;\;\; \\
+   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] }
+    & \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}
       } \\
@@ -117,11 +122,11 @@
     %
     \intertext{Since the horizontal scale factors do not depend on the vertical coordinate,
-    the last term of the first line and the first term of the last line cancel, while
-    the second line reduces to a single vertical derivative, so it becomes:}
+    the two terms on the second line cancel, while
+    the third line reduces to a single vertical derivative, so it becomes:}
   %
-    & =\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. \\
+    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:}
+    \intertext{In other words, the horizontal/vertical Laplacian operator in the ($i$,$s$) plane takes the following form:}
   \end{array}
   } \\
@@ -169,11 +174,14 @@
   \left[ {{
         \begin{array}{*{20}c}
-          {1+a_1 ^2} \hfill & {-a_1 a_2 } \hfill & {-a_1 } \hfill \\
-          {-a_1 a_2 } \hfill & {1+a_2 ^2} \hfill & {-a_2 } \hfill \\
-          {-a_1 } \hfill & {-a_2 } \hfill & {\varepsilon +a_1 ^2+a_2 ^2} \hfill \\
+          {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 the isopycnal slopes in ($\textbf{i}$, $\textbf{j}$) directions, relative to geopotentials:
+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}
@@ -182,7 +190,9 @@
   \right)\left( {\frac{\partial \rho }{\partial k}} \right)^{-1}
 \]
-
-In practice, isopycnal slopes are generally less than $10^{-2}$ in the ocean,
-so $\textbf {A}_{\textbf I}$ can be simplified appreciably \citep{cox_OM87}:
+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{apdx:B4}
@@ -226,6 +236,6 @@
 The isopycnal diffusion operator \autoref{apdx:B4},
 \autoref{apdx:B_ldfiso} conserves tracer quantity and dissipates its square.
-The demonstration of the first property is trivial as \autoref{apdx:B4} is the divergence of fluxes.
-Let us demonstrate the second one:
+As \autoref{apdx:B4} 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
@@ -246,5 +256,5 @@
              j}-a_2 \frac{\partial T}{\partial k}} \right)^2}
              +\varepsilon \left(\frac{\partial T}{\partial k}\right) ^2\right]      \\
-           & \geq 0
+           & \geq 0 . 
   \end{array}
              }
@@ -275,6 +285,7 @@
 \end{equation}
 
-where ($r_1$, $r_2$) are the isopycnal slopes in ($\textbf{i}$, $\textbf{j}$) directions,
-relative to $s$-coordinate surfaces:
+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}
@@ -284,5 +295,5 @@
 \]
 
-To prove \autoref{apdx:B5} by direct re-expression of \autoref{apdx:B_ldfiso} is straightforward, but laborious.
+To prove \autoref{apdx:B_ldfiso_s} by direct re-expression of \autoref{apdx:B_ldfiso} is straightforward, but laborious.
 An easier way is first to note (by reversing the derivation of \autoref{sec:B_2} from \autoref{sec:B_1} ) that
 the weak-slope operator may be \emph{exactly} reexpressed in non-orthogonal $i,j,\rho$-coordinates as
@@ -306,5 +317,5 @@
 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 the same way as the transformation of horizontal/vertical Laplacian diffusion in $z$-coordinates in
 \autoref{sec:B_1} onto $s$-coordinates is exact, however steep the $s$-surfaces.
 
@@ -316,5 +327,5 @@
 \label{sec:B_3}
 
-The second order momentum diffusion operator (Laplacian) in the $z$-coordinate is found by
+The second order momentum diffusion operator (Laplacian) in $z$-coordinates is found by
 applying \autoref{eq:PE_lap_vector}, the expression for the Laplacian of a vector,
 to the horizontal velocity vector:
@@ -361,7 +372,7 @@
 \end{align*}
 Using \autoref{eq:PE_div}, the definition of the horizontal divergence,
-the third componant of the second vector is obviously zero and thus :
+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 \right) + \frac {1}{e_3 } \frac {\partial }{\partial k} \left( {\frac {1}{e_3 } \frac{\partial {\textbf{ U}}_h }{\partial k}} \right)
+  \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) . 
 \]
 
@@ -379,5 +390,5 @@
   - \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) \\
+      \frac{\partial {\mathrm {\mathbf U}}_h }{\partial k}} \right) , \\
 \end{equation}
 that is, in expanded form:
@@ -386,9 +397,9 @@
   & = \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 u}{\partial k}      \\
+    +\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 v}{\partial k}
+    +\frac{1}{e_3} \frac{\partial }{\partial k} \left( \frac{A^{vm}}{e_3} \frac{\partial v}{\partial k} \right) .
 \end{align*}
 
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/annex_D.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/annex_D.tex	(revision 11352)
+++ 	(revision )
@@ -1,207 +1,0 @@
-\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/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/annex_DOMAINcfg.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/annex_DOMAINcfg.tex	(revision 11353)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/annex_DOMAINcfg.tex	(revision 11353)
@@ -0,0 +1,563 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+% ================================================================
+% Appendix DOMAINcfg : A brief guide to the DOMAINcfg tool
+% ================================================================
+\chapter{A brief guide to the DOMAINcfg tool}
+\label{apdx:DOMAINcfg}
+
+\minitoc
+\vfill
+\begin{figure}[b]
+\subsubsection*{Changes record}
+\begin{tabular}{m{0.08\linewidth}||m{0.32\linewidth}|m{0.6\linewidth}}
+    Release   & Author(s)     & Modifications \\
+\hline
+    {\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 }  \\
+\end{tabular}
+\end{figure}
+
+\newpage
+
+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.
+
+% -------------------------------------------------------------------------------------------------------------
+%        Choice of horizontal grid
+% -------------------------------------------------------------------------------------------------------------
+\section{Choice of horizontal grid}
+\label{sec:DOMCFG_hor}
+
+%--------------------------------------------namdom-------------------------------------------------------
+
+\nlst{namdom_domcfg} 
+%--------------------------------------------------------------------------------------------------------------
+
+The user has three options available in defining a horizontal grid, which involve the
+namelist variable \np{jphgr\_mesh} of the \ngn{namdom} (\forcode{DOMAINcfg} variant only)
+namelist.
+
+\begin{description}
+ \item[\np{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}=1 to 5] A few simple analytical grids are provided (see below). 
+  For other analytical grids, the \textit{domhgr.f90} module (\forcode{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}=1, the grid (expressed in degrees) is regular in space, 
+with grid sizes specified by parameters \np{ppe1\_deg} and \np{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}=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} 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}=1 or 4), the grid position is defined by the 
+longitude and latitude of the south-westernmost point (\np{ppglamt0} 
+and \np{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} = 2, 3, 5. The domain is either an $f$-plane (\np{jphgr\_mesh} = 2, 
+Coriolis factor is constant) or a beta-plane (\np{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} and \np{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} is ignored. \np{ppgphi0} is used to set the reference 
+latitude for computation of the Coriolis parameter. In the case of the beta plane, 
+\np{ppgphi0} corresponds to the center of the domain. Finally, the special case 
+\np{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). 
+
+% -------------------------------------------------------------------------------------------------------------
+%        vertical reference coordinate transformation
+% -------------------------------------------------------------------------------------------------------------
+\section{Vertical grid}
+\label{sec:DOMCFG_vert}
+\subsection{Vertical reference coordinate}
+\label{sec:DOMCFG_zref}
+
+%>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+\begin{figure}[!tb]
+  \begin{center}
+    \includegraphics[width=\textwidth]{Fig_zgr}
+    \caption{
+      \protect\label{fig:DOMCFG_zgr}
+      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.
+    }
+  \end{center}
+\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: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 \ngn{namdom} namelist
+(\forcode{DOMAINcfg} variant).
+
+It is possible to define a simple regular vertical grid by giving zero stretching
+(\np{ppacr}\forcode{ = 0}).  In that case, the parameters \jp{jpk} (number of $w$-levels)
+and \np{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{ldbletanh}\forcode{ = .true.}) 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{ln\_isfcav}\forcode{ = .true.}), 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}, \np{ppa0}, \np{ppa1}, \np{ppkth} in \ngn{namcfg} 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}~$=$~\np{ppa0}~$=$~\np{ppa1}~$=
+999999$., in \ngn{namcfg} namelist, and specifies instead the four following parameters:
+\begin{itemize}
+\item
+  \np{ppacr}~$= h_{cr}$: stretching factor (nondimensional).
+  The larger \np{ppacr}, the smaller the stretching.
+  Values from $3$ to $10$ are usual.
+\item
+  \np{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}: minimum thickness for the top layer (in meters).
+\item
+  \np{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}~$= 9$, \np{ppkth}~$= 23.563$, \np{ppdzmin}~$= 6~m$,
+\np{pphmax}~$= 5750~m$.
+
+%% %>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+\begin{table}
+  \begin{center}
+    \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}
+  \end{center}
+  \caption{
+    \protect\label{tab:DOMCFG_orca_zgr}
+    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}
+  }
+\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} (found in \ngn{namdom} namelist (\forcode{DOMAINCFG} variant) ):
+\begin{description}
+\item[\np{nn\_bathy}\forcode{ = 0}]:
+  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}.
+\item[\np{nn\_bathy}\forcode{ = -1}]:
+  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{nn\_bathy}\forcode{ = 1}]:
+  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{ln\_isfcav}\forcode{ = .true.}.
+  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}
+%%%
+ 
+% -------------------------------------------------------------------------------------------------------------
+%        z-coordinate with constant thickness
+% -------------------------------------------------------------------------------------------------------------
+\subsubsection[$Z$-coordinate with uniform thickness levels (\forcode{ln_zco = .true.})]
+{$Z$-coordinate with uniform thickness levels (\protect\np{ln\_zco}\forcode{ = .true.})}
+\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.
+
+% -------------------------------------------------------------------------------------------------------------
+%        z-coordinate with partial step
+% -------------------------------------------------------------------------------------------------------------
+\subsubsection[$Z$-coordinate with partial step (\forcode{ln_zps = .true.})]
+{$Z$-coordinate with partial step (\protect\np{ln\_zps}\forcode{ = .true.})}
+\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 \ngn{namdom} namelist
+(\forcode{DOMMAINCFG} variant), such as the maximum depth \np{pphmax} in partial steps.
+
+For example, with \np{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} (thickness in
+meters, usually $20~m$) or $e_{3t}(jk)*$\np{rn\_e3zps\_rat} (a fraction, usually 10\%, of
+the default thickness $e_{3t}(jk)$).
+
+% -------------------------------------------------------------------------------------------------------------
+%        s-coordinate
+% -------------------------------------------------------------------------------------------------------------
+\subsubsection[$S$-coordinate (\forcode{ln_sco = .true.})]
+{$S$-coordinate (\protect\np{ln\_sco}\forcode{ = .true.})}
+\label{sec:DOMCFG_sco}
+%------------------------------------------nam_zgr_sco---------------------------------------------------
+%
+\nlst{namzgr_sco_domcfg} 
+%--------------------------------------------------------------------------------------------------------------
+Options are defined in \ngn{namzgr\_sco} (\forcode{DOMAINcfg} only).
+In $s$-coordinate (\np{ln\_sco}\forcode{ = .true.}), 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:z_zps_s_sps}) or an envelop bathymetry can be defined (\autoref{fig:z_zps_s_sps}).
+The namelist parameter \np{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} and \np{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{ln\_s\_SH94}\forcode{ = .false.} and \np{ln\_s\_SF12}\forcode{ = .false.}).
+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: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{ln\_s\_SH94}\forcode{ = .true.}),
+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:SH94_2}
+\]
+
+%% %>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+\begin{figure}[!ht]
+  \begin{center}
+    \includegraphics[width=\textwidth]{Fig_sco_function}
+    \caption{
+      \protect\label{fig:sco_function}
+      Examples of the stretching function applied to a seamount;
+      from left to right: surface, surface and bottom, and bottom intensified resolutions
+    }
+  \end{center}
+\end{figure}
+%% %>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+
+where $H_c$ is the critical depth (\np{rn\_hc}) at which the coordinate transitions from pure $\sigma$ to
+the stretched coordinate, and $\theta$ (\np{rn\_theta}) and $b$ (\np{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:sco_function}).
+
+Another example has been provided at version 3.5 (\np{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: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}) that stretches towards
+the surface ($\alpha > 1.0$) or the bottom ($\alpha < 1.0$) and
+user prescribed surface (\np{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} and \np{rn\_zb\_b} are $a$ and $b$ respectively.
+
+%% %>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+\begin{figure}[!ht]
+  \includegraphics[width=\textwidth]{Fig_DOM_compare_coordinates_surface}
+  \caption{
+    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: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} 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.
+
+% -------------------------------------------------------------------------------------------------------------
+%        z*- or s*-coordinate
+% -------------------------------------------------------------------------------------------------------------
+\subsubsection[\zstar- or \sstar-coordinate (\forcode{ln_linssh = .false.})]
+{\zstar- or \sstar-coordinate (\protect\np{ln\_linssh}\forcode{ = .false.})}
+\label{subsec:DOMCFG_zgr_star}
+
+This option is described in the Report by Levier \textit{et al.} (2007), available on the \NEMO web site.
+
+\biblio
+
+\pindex
+
+\end{document}
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_ASM.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_ASM.tex	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_ASM.tex	(revision 11353)
@@ -8,12 +8,20 @@
 \label{chap:ASM}
 
-Authors: D. Lea,  M. Martin, K. Mogensen, A. Weaver, ...   % do we keep
+\minitoc
 
-\minitoc
+\vfill
+\begin{figure}[b]
+\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.4} & {\em D. J. Lea, M. Martin, K. Mogensen, A. Weaver} & {\em Initial version}  \\
+\end{tabular}
+\end{figure}
 
 \newpage
 
 The ASM code adds the functionality to apply increments to the model variables: temperature, salinity,
-sea surface height, velocity and sea ice concentration. 
+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.
@@ -56,5 +64,5 @@
 Typically the increments are spread evenly over the full window.
 In addition, two different weighting functions have been implemented.
-The first function employs constant weights, 
+The first function (namelist option \np{niaufn} = 0) employs constant weights,
 \begin{align}
   \label{eq:F1_i}
@@ -66,8 +74,8 @@
     0     &    {\mathrm if} \; \; \; t_{i} > t_{n}
   \end{array}
-            \right. 
+            \right.
 \end{align}
 where $M = m-n$.
-The second function employs peaked hat-like weights in order to give maximum weight in the centre of the sub-window,
+The second function (namelist option \np{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}
@@ -83,5 +91,5 @@
                                    \right.
 \end{align}
-where $\alpha^{-1} = \sum_{i=1}^{M/2} 2i$ and $M$ is assumed to be even. 
+where $\alpha^{-1} = \sum_{i=1}^{M/2} 2i$ and $M$ is assumed to be even.
 The weights described by \autoref{eq:F2_i} provide a smoother transition of the analysis trajectory from
 one assimilation cycle to the next than that described by \autoref{eq:F1_i}.
@@ -92,6 +100,9 @@
 \label{sec:ASM_div_dmp}
 
-The velocity increments may be initialized by the iterative application of a divergence damping operator.
-In iteration step $n$ new estimates of velocity increments $u^{n}_I$ and $v^{n}_I$ are updated by:
+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}
@@ -105,5 +116,7 @@
   \right.,
 \end{equation}
-where
+
+where the divergence is defined as
+
 \[
   % \label{eq:asm_div}
@@ -112,5 +125,6 @@
       +\delta_j \left[ {e_{1v}\,e_{3v}\,v^{n-1}_I} \right]} \right).
 \]
-By the application of \autoref{eq:asm_dmp} and \autoref{eq:asm_dmp} the divergence is filtered in each iteration,
+
+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
@@ -122,6 +136,5 @@
 The divergence damping is activated by assigning to \np{nn\_divdmp} in the \textit{nam\_asminc} namelist
 a value greater than zero.
-By choosing this value to be of the order of 100 the increments in
-the vertical velocity will be significantly reduced.
+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.
 
 
@@ -131,8 +144,8 @@
 \label{sec:ASM_details}
 
-Here we show an example \ngn{namasm} namelist and the header of an example assimilation increments file on
+Here we show an example \ngn{nam\_asminc} namelist and the header of an example assimilation increments file on
 the ORCA2 grid.
 
-%------------------------------------------namasm-----------------------------------------------------
+%------------------------------------------nam_asminc-----------------------------------------------------
 %
 \nlst{nam_asminc}
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_DIA.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_DIA.tex	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_DIA.tex	(revision 11353)
@@ -10,4 +10,17 @@
 \minitoc
 
+\vfill
+\begin{figure}[b]
+\subsubsection*{Changes record}
+\begin{tabular}{l||l|m{0.65\linewidth}}
+    Release   & Author        & Modifications \\
+    {\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 }  \\ 
+\end{tabular}
+\end{figure} 
+
 \newpage
 
@@ -15,5 +28,5 @@
 %       Old Model Output 
 % ================================================================
-\section{Old model output (default)}
+\section{Model output}
 \label{sec:DIA_io_old}
 
@@ -1494,5 +1507,5 @@
 \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}, \np{ln\_vor\_trd}, and \np{ln\_tra\_mxl} are not working,
-and none of the options have been tested with variable volume (\ie \key{vvl} defined).
+and none of the options have been tested with variable volume (\ie \np{ln\_linssh}\forcode{ = .true.}).
 
 % -------------------------------------------------------------------------------------------------------------
@@ -1930,5 +1943,5 @@
   
 Third, the discretisation of \autoref{eq:steric_Bq} depends on the type of free surface which is considered.
-In the non linear free surface case, \ie \key{vvl} defined, it is given by
+In the non linear free surface case, \ie \np{ln\_linssh}\forcode{ = .true.}, it is given by
 
 \[
@@ -1969,12 +1982,11 @@
 where $S_o$ and $p_o$ are the initial salinity and pressure, respectively.
 
-Both steric and thermosteric sea level are computed in \mdl{diaar5} which needs the \key{diaar5} defined to
-be called.
+Both steric and thermosteric sea level are computed in \mdl{diaar5}.
 
 % -------------------------------------------------------------------------------------------------------------
 %       Other Diagnostics
 % -------------------------------------------------------------------------------------------------------------
-\section[Other diagnostics (\texttt{\textbf{key\_diahth}}, \texttt{\textbf{key\_diaar5}})]
-{Other diagnostics (\protect\key{diahth}, \protect\key{diaar5})}
+\section[Other diagnostics]
+{Other diagnostics}
 \label{sec:DIA_diag_others}
 
@@ -1995,23 +2007,4 @@
 - the depth of the thermocline (maximum of the vertical temperature gradient) (\mdl{diahth})
 
-% -----------------------------------------------------------
-%     Poleward heat and salt transports
-% -----------------------------------------------------------
-
-\subsection[Poleward heat and salt transports (\textit{diaptr.F90})]
-{Poleward heat and salt transports (\protect\mdl{diaptr})}
-
-%------------------------------------------namptr-----------------------------------------
-
-\nlst{namptr} 
-%-----------------------------------------------------------------------------------------
-
-The poleward heat and salt transports, their advective and diffusive component,
-and the meriodional stream function can be computed on-line in \mdl{diaptr} \np{ln\_diaptr} to true
-(see the \textit{\ngn{namptr} } namelist below).
-When \np{ln\_subbas}\forcode{ = .true.}, 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:mask_subasins}).
 
 %>>>>>>>>>>>>>>>>>>>>>>>>>>>>
@@ -2034,11 +2027,23 @@
 %       CMIP specific diagnostics 
 % -----------------------------------------------------------
-\subsection[CMIP specific diagnostics (\textit{diaar5.F90})]
+\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}.
-They corresponds to outputs that are required for AR5 simulations (CMIP5)
+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).
-Activating those outputs requires to define the \key{diaar5} CPP key.
+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{ln\_diaptr}\forcode{ = .true.} 
+(see the \textit{\ngn{namptr} } 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{ln\_subbas}\forcode{ = .true.}, 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:mask_subasins}).
+
+%------------------------------------------namptr-----------------------------------------
+
+\nlst{namptr} 
+%-----------------------------------------------------------------------------------------
 
 % -----------------------------------------------------------
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_DOM.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_DOM.tex	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_DOM.tex	(revision 11353)
@@ -18,10 +18,21 @@
 %     - domclo:  closed sea and lakes.... management of closea sea area : specific to global configuration, both forced and coupled
 
+\vfill
+\begin{figure}[b]
+\subsubsection*{Changes record}
+\begin{tabular}{m{0.08\linewidth}||m{0.32\linewidth}|m{0.6\linewidth}}
+    Release   & Author(s)     & Modifications \\
+\hline
+    {\em 4.0} & {\em Simon M{\"u}ller \& Andrew Coward} & {\em Compatibility changes for v4.0. Major simplication has moved many of the options to external domain configuration tools. For now this information has been retained in \autoref{apdx:DOMAINcfg} }  \\
+    {\em 3.x} & {\em Sebastien Masson, Gurvan Madec \& Rashid Benshila } & {\em }  \\
+\end{tabular}
+\end{figure}
+
 \newpage
 
 Having defined the continuous equations in \autoref{chap:PE} and chosen a time discretization \autoref{chap:STP},
-we need to choose a discretization on a grid, and numerical algorithms.
+we need to choose a grid for spatial discretization and related numerical algorithms.
 In the present chapter, we provide a general description of the staggered grid used in \NEMO,
-and other information relevant to the main directory routines as well as the DOM (DOMain) directory.
+and other relevant information about the DOM (DOMain) source-code modules .
 
 % ================================================================
@@ -55,5 +66,5 @@
 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 space directions.
+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
@@ -71,5 +82,5 @@
 Each scale factor is defined as the local analytical value provided by \autoref{eq:scale_factors}.
 As a result, the mesh on which partial derivatives $\pd[]{\lambda}$, $\pd[]{\varphi}$ and
-$\pd[]{z}$ are evaluated in a uniform mesh with a grid size of unity.
+$\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.
@@ -79,5 +90,5 @@
 the continuous properties (see \autoref{apdx:C}).
 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 sum of the relevant scale factors
+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).
 
@@ -87,5 +98,5 @@
     \begin{tabular}{|p{46pt}|p{56pt}|p{56pt}|p{56pt}|}
       \hline
-      T	& $i 		 $ & $j      $ & $k      $ \\
+      t	& $i 		 $ & $j      $ & $k      $ \\
       \hline
       u	& $i + 1/2$ & $j      $ & $k      $ \\
@@ -107,10 +118,42 @@
       \protect\label{tab:cell}
       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 equation.
-      In the code, the indexing uses integer values only and has a reverse direction in the vertical
+      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})
     }
   \end{center}
 \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:zgr_e3}.
+%>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+\begin{figure}[!t]
+  \begin{center}
+    \includegraphics[width=\textwidth]{Fig_zgr_e3}
+    \caption{
+      \protect\label{fig:zgr_e3}
+      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$.
+    }
+  \end{center}
+\end{figure}
 %>>>>>>>>>>>>>>>>>>>>>>>>>>>>
 
@@ -132,5 +175,5 @@
 Following \autoref{eq:PE_grad} and \autoref{eq:PE_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 $t$-point.
+its Laplacian is defined at the $t$-point.
 These operators have the following discrete forms in the curvilinear $s$-coordinates system:
 \[
@@ -171,6 +214,6 @@
 \end{equation}
 
-The vertical average over the whole water column denoted by an overbar becomes for a quantity $q$ which
-is a masked field (i.e. equal to zero inside solid area):
+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}
@@ -178,5 +221,5 @@
 \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 $k^o$ refers to a summation over
+$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$).
 
@@ -193,6 +236,6 @@
 vector points $(u,v,w)$.
 
-Let $a$ and $b$ be two fields defined on the mesh, with value zero inside continental area.
-Using integration by parts it can be shown that the differencing operators ($\delta_i$, $\delta_j$ and $\delta_k$)
+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
@@ -228,10 +271,10 @@
 %>>>>>>>>>>>>>>>>>>>>>>>>>>>>
 
-The array representation used in the \fortran code requires an integer indexing while
-the analytical definition of the mesh (see \autoref{subsec:DOM_cell}) is associated with the use of
-integer values for $t$-points and both integer and integer and a half values for all the other points.
-Therefore a specific integer indexing must be defined for points other than $t$-points
+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 changed so that the surface level is at $k = 1$.
+Furthermore, the direction of the vertical indexing has been reversed and the surface level set at $k = 1$.
 
 % -----------------------------------
@@ -253,19 +296,18 @@
 \label{subsec:DOM_Num_Index_vertical}
 
-In the vertical, the chosen indexing requires special attention since the $k$-axis is re-orientated downward in
-the \fortran code compared to the indexing used in the semi -discrete equations and
+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 $t$-level just below
+The sea surface corresponds to the $w$-level $k = 1$, which is the same index as the $t$-level just below
 (\autoref{fig:index_vert}).
-The last $w$-level ($k = jpk$) either corresponds to the ocean floor or is inside the bathymetry while
-the last $t$-level is always inside the bathymetry (\autoref{fig:index_vert}).
-Note that for an increasing $k$ index, a $w$-point and the $t$-point just below have the same $k$ index,
-in opposition to what is done in the horizontal plane where
-it is the $t$-point and the nearest velocity points in the direction of the horizontal axis that
-have the same $i$ or $j$ index
+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: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:index_hor} and \autoref{fig:index_vert}).
 Since the scale factors are chosen to be strictly positive,
-a \textit{minus sign} appears in the \fortran code \textit{before all the vertical derivatives} of
-the discrete equations given in this documentation.
+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.
 
 %>>>>>>>>>>>>>>>>>>>>>>>>>>>>
@@ -276,6 +318,6 @@
       \protect\label{fig:index_vert}
       Vertical integer indexing used in the \fortran code.
-      Note that the $k$-axis is orientated downward.
-      The dashed area indicates the cell in which variables contained in arrays have the same $k$-index.
+      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.
     }
   \end{center}
@@ -283,190 +325,146 @@
 %>>>>>>>>>>>>>>>>>>>>>>>>>>>>
 
+% -------------------------------------------------------------------------------------------------------------
+%        Domain configuration
+% -------------------------------------------------------------------------------------------------------------
+\section{Spatial domain configuration}
+\label{subsec:DOM_config}
+
+\nlst{namcfg}
+
+Two typical methods are available to specify the spatial domain
+configuration; they can be selected using parameter \np{ln\_read\_cfg}
+parameter in namelist \ngn{namcfg}. 
+
+If \np{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} parameter in
+namelist \ngn{namcfg}.
+
+If \np{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 bathmetries and 
+performing a vertical discretization 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 discretization has be incorporated 
+into an external tool (\path{tools/DOMAINcfg}) which is briefly described in \autoref{apdx:DOMAINcfg}.
+
+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} file or set by code
+inserted into user-supplied versions of the \mdl{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}).
+
 % -----------------------------------
 %        Domain Size
 % -----------------------------------
-\subsubsection{Domain size}
+\subsection{Domain size}
 \label{subsec:DOM_size}
 
-The total size of the computational domain is set by the parameters \np{jpiglo},
-\np{jpjglo} and \np{jpkglo} in the $i$, $j$ and $k$ directions respectively.
-Parameters $jpi$ and $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}).
-
-% ================================================================
-% Domain: List of fields needed
-% ================================================================
-\section{Needed fields}
-\label{sec:DOM_fields}
-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 values of as indicated in \autoref{tab:cell}.
-The associated scale factors are defined using the analytical first derivative of the transformation
-\autoref{eq:scale_factors}.
-Necessary fields for configuration definition are:
-
-\begin{itemize}
-\item
-  Geographic position:
-  longitude with \texttt{glamt}, \texttt{glamu}, \texttt{glamv}, \texttt{glamf} and
-  latitude  with \texttt{gphit}, \texttt{gphiu}, \texttt{gphiv}, \texttt{gphif}
-  (all respectively at T, U, V and F point)
-\item
-  Coriolis parameter (if domain not on the sphere): \texttt{ff\_f} and \texttt{ff\_t}
-  (at T and F point)
-\item
-  Scale factors:
-  \texttt{e1t}, \texttt{e1u}, \texttt{e1v} and \texttt{e1f} (on i direction),
-  \texttt{e2t}, \texttt{e2u}, \texttt{e2v} and \texttt{e2f} (on j direction) and
-  \texttt{ie1e2u\_v}, \texttt{e1e2u}, \texttt{e1e2v}. \\
-  \texttt{e1e2u}, \texttt{e1e2v} are u and v surfaces (if gridsize reduction in some straits), 
-  \texttt{ie1e2u\_v} is to flag set u and v surfaces are neither read nor computed.
-\end{itemize}
- 
-These fields can be read in an domain input file which name is setted in \np{cn\_domcfg} parameter specified in
-\ngn{namcfg}.
-
-\nlst{namcfg}
-
-Or they can be defined in an analytical way in \path{MY_SRC} directory of the configuration.
-For Reference Configurations of NEMO input domain files are supplied by NEMO System Team.
-For analytical definition of input fields two routines are supplied: \mdl{usrdef\_hgr} and \mdl{usrdef\_zgr}.
-They are an example of GYRE configuration parameters, and they are available in \path{src/OCE/USR} directory,
-they provide the horizontal and vertical mesh.
-% -------------------------------------------------------------------------------------------------------------
-%        Needed fields 
-% -------------------------------------------------------------------------------------------------------------
-%\subsection{List of needed fields to build DOMAIN}
-%\label{subsec:DOM_fields_list}
-
+The total size of the computational domain is set by the parameters
+\np{jpiglo}, \np{jpjglo} and \np{jpkglo} for the $i$, $j$ and $k$
+directions, respectively. Note, that the variables \forcode{jpi} and \forcode{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},
+and the nominal resolution through parameter \np{nn\_cfg} (unless in
+the input file both of variables \forcode{ORCA} and \forcode{ORCA_index}
+are present, in which case \np{cn\_cfg} and \np{nn\_cfg} are set from these
+values accordingly).
+
+The global lateral boundary condition type is selected from 8 options
+using parameter \np{jperio}. See \autoref{sec:LBC_jperio} for
+details on the available options and the corresponding values for
+\np{jperio}.
 
 % ================================================================
 % Domain: Horizontal Grid (mesh) 
 % ================================================================
-\section[Horizontal grid mesh (\textit{domhgr.F90})]
-{Horizontal grid mesh (\protect\mdl{domhgr})}
-\label{sec:DOM_hgr}
-
-% -------------------------------------------------------------------------------------------------------------
-%        Coordinates and scale factors 
-% -------------------------------------------------------------------------------------------------------------
-\subsection{Coordinates and scale factors}
-\label{subsec:DOM_hgr_coord_e}
-
-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 values of as indicated in \autoref{tab:cell}.
-The associated scale factors are defined using the analytical first derivative of the transformation
-\autoref{eq:scale_factors}.
-These definitions are done in two modules, \mdl{domhgr} and \mdl{domzgr},
-which provide the horizontal and vertical meshes, respectively.
-This section deals with the horizontal mesh parameters.
-
-In a horizontal plane, the location of all the model grid points is defined from
-the analytical expressions of the longitude $\lambda$ and latitude $\varphi$ as a function of $(i,j)$.
-The horizontal scale factors are calculated using \autoref{eq:scale_factors}.
-For example, when the longitude and latitude are function of a single value
-($i$ and $j$, respectively) (geographical configuration of the mesh),
-the horizontal mesh definition reduces to define the wanted $\lambda(i)$, $\varphi(j)$,
-and their derivatives $\lambda'(i) \ \varphi'(j)$ in the \mdl{domhgr} module.
-The model computes the grid-point positions and scale factors in the horizontal plane as follows:
-\begin{align*}
-   \lambda_t &\equiv \text{glamt} =      \lambda (i      )
-  &\varphi_t &\equiv \text{gphit} =      \varphi (j      ) \\
-   \lambda_u &\equiv \text{glamu} =      \lambda (i + 1/2)
-  &\varphi_u &\equiv \text{gphiu} =      \varphi (j      ) \\
-   \lambda_v &\equiv \text{glamv} =      \lambda (i      )
-  &\varphi_v &\equiv \text{gphiv} =      \varphi (j + 1/2) \\
-   \lambda_f &\equiv \text{glamf} =      \lambda (i + 1/2)
-  &\varphi_f &\equiv \text{gphif} =      \varphi (j + 1/2) \\
-   e_{1t}    &\equiv \text{e1t}   = r_a |\lambda'(i      ) \; \cos\varphi(j      ) |
-  &e_{2t}    &\equiv \text{e2t}   = r_a |\varphi'(j      )                         | \\
-   e_{1u}    &\equiv \text{e1t}   = r_a |\lambda'(i + 1/2) \; \cos\varphi(j      ) |
-  &e_{2u}    &\equiv \text{e2t}   = r_a |\varphi'(j      )                         | \\
-   e_{1v}    &\equiv \text{e1t}   = r_a |\lambda'(i      ) \; \cos\varphi(j + 1/2) |
-  &e_{2v}    &\equiv \text{e2t}   = r_a |\varphi'(j + 1/2)                         | \\
-   e_{1f}    &\equiv \text{e1t}   = r_a |\lambda'(i + 1/2) \; \cos\varphi(j + 1/2) |
-  &e_{2f}    &\equiv \text{e2t}   = r_a |\varphi'(j + 1/2)                         |
-\end{align*}
-where the last letter of each computational name indicates the grid point considered and
-$r_a$ is the earth radius (defined in \mdl{phycst} along with all universal constants).
-Note that the horizontal position of and scale factors at $w$-points are exactly equal to those of $t$-points,
-thus no specific arrays are defined at $w$-points.
-
-Note that the definition of the scale factors
-(\ie as the analytical first derivative of the transformation that
-gives $(\lambda,\varphi,z)$ as a function of $(i,j,k)$)
-is specific to the \NEMO model \citep{marti.madec.ea_JGR92}.
-As an example, $e_{1t}$ 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:zgr_e3}.
-%>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-\begin{figure}[!t]
-  \begin{center}
-    \includegraphics[width=\textwidth]{Fig_zgr_e3}
-    \caption{
-      \protect\label{fig:zgr_e3}
-      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$.
-    }
-  \end{center}
-\end{figure}
-%>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-
-% -------------------------------------------------------------------------------------------------------------
-%        Choice of horizontal grid
-% -------------------------------------------------------------------------------------------------------------
-\subsection{Choice of horizontal grid}
-\label{subsec:DOM_hgr_msh_choice}
-
-% -------------------------------------------------------------------------------------------------------------
-%        Grid files
-% -------------------------------------------------------------------------------------------------------------
-\subsection{Output grid files}
-\label{subsec:DOM_hgr_files}
-
-All the arrays relating to a particular ocean model configuration (grid-point position, scale factors, masks)
-can be saved in files if \np{nn\_msh} $\not = 0$ (namelist variable in \ngn{namdom}).
-This can be particularly useful for plots and off-line diagnostics.
-In some cases, the user may choose to make a local modification of a scale factor in the code.
-This is the case in global configurations when restricting the width of a specific strait
-(usually a one-grid-point strait that happens to be too wide due to insufficient model resolution).
-An example is Gibraltar Strait in the ORCA2 configuration.
-When such modifications are done,
-the output grid written when \np{nn\_msh} $\not = 0$ is no more equal to the input grid.
+\subsection{Horizontal grid mesh (\protect\mdl{domhgr})}
+\label{subsec:DOM_hgr}
+
+% ================================================================
+% Domain: List of hgr-related fields needed
+% ================================================================
+\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{Verbatim}[fontsize=\tiny]
+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{Verbatim}
+
+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 Table \autoref{tab: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{Verbatim}[fontsize=\tiny]
+                                         /* 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{Verbatim}
+
+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 $\texttt{e1u} * \texttt{e2u}$ and $\texttt{e1v} * \texttt{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} 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.
+
 
 % ================================================================
 % Domain: Vertical Grid (domzgr)
 % ================================================================
-\section[Vertical grid (\textit{domzgr.F90})]
+\subsection[Vertical grid (\textit{domzgr.F90})]
 {Vertical grid (\protect\mdl{domzgr})}
-\label{sec:DOM_zgr}
-%-----------------------------------------nam_zgr & namdom-------------------------------------------
-%
-%\nlst{namzgr} 
-
-\nlst{namdom} 
+\label{subsec:DOM_zgr}
+%-----------------------------------------namdom-------------------------------------------
+\nlst{namdom}
 %-------------------------------------------------------------------------------------------------------------
 
-Variables are defined through the \ngn{namzgr} and \ngn{namdom} namelists.
 In the vertical, the model mesh is determined by four things: 
-(1) the bathymetry given in meters; 
-(2) the number of levels of the model (\jp{jpk}); 
-(3) the analytical transformation $z(i,j,k)$ and the vertical scale factors (derivatives of the transformation); and
-(4) the masking system, \ie the number of wet model levels at each 
-$(i,j)$ column of points.
+\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}
 
 %>>>>>>>>>>>>>>>>>>>>>>>>>>>>
@@ -489,510 +487,108 @@
 %>>>>>>>>>>>>>>>>>>>>>>>>>>>>
 
-The choice of a vertical coordinate, even if it is made through \ngn{namzgr} namelist parameters, 
-must be done once of all at the beginning of an experiment.
-It is not intended as an option which can be enabled or disabled in the middle of an experiment.
-Three main choices are offered (\autoref{fig:z_zps_s_sps}):
-$z$-coordinate with full step bathymetry (\np{ln\_zco}\forcode{ = .true.}),
-$z$-coordinate with partial step bathymetry (\np{ln\_zps}\forcode{ = .true.}),
-or generalized, $s$-coordinate (\np{ln\_sco}\forcode{ = .true.}).
-Hybridation of the three main coordinates are available:
-$s-z$ or $s-zps$ coordinate (\autoref{fig:z_zps_s_sps} and \autoref{fig:z_zps_s_sps}).
-By default a non-linear free surface is used: the coordinate follow the time-variation of the free surface so that
-the transformation is time dependent: $z(i,j,k,t)$ (\autoref{fig:z_zps_s_sps}).
-When a linear free surface is assumed (\np{ln\_linssh}\forcode{ = .true.}),
-the vertical coordinate 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).
-The last choice in terms of vertical coordinate concerns the presence (or not) in
-the model domain of ocean cavities beneath ice shelves.
-Setting \np{ln\_isfcav} to true allows to manage ocean cavities, otherwise they are filled in.
-This option is currently only available in $z$- or $zps$-coordinate,
-and partial step are also applied at the ocean/ice shelf interface.
-
-Contrary to the horizontal grid, the vertical grid is computed in the code and no provision is made for
-reading it from a file.
-The only input file is the bathymetry (in meters) (\ifile{bathy\_meter})
-\footnote{
-  N.B. in full step $z$-coordinate, a \ifile{bathy\_level} file can replace the \ifile{bathy\_meter} file,
-  so that the computation of the number of wet ocean point in each water column is by-passed}.
-If \np{ln\_isfcav}\forcode{ = .true.}, an extra file input file (\ifile{isf\_draft\_meter}) describing
-the ice shelf draft (in meters) is needed.
-
-After reading the bathymetry, the algorithm for vertical grid definition differs between the different options:
-\begin{description}
-\item[\textit{zco}]
-  set a reference coordinate transformation $z_0(k)$, and set $z(i,j,k,t) = z_0(k)$.
-\item[\textit{zps}]
-  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[\textit{sco}]
-  smooth the bathymetry to fulfill the hydrostatic consistency criteria and
-  set the three-dimensional transformation.
-\item[\textit{s-z} and \textit{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}
-%%%
-\gmcomment{   add the description of the smoothing:  envelop topography...}
-%%%
-
-Unless a linear free surface is used (\np{ln\_linssh}\forcode{ = .false.}),
-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 using a fixed reference coordinate system which
-computer names have a $\_0$ suffix.
-When the linear free surface option is used (\np{ln\_linssh}\forcode{ = .true.}), \textit{before},
-\textit{now} and \textit{after} arrays are simply set one for all to their reference counterpart.
-
-% -------------------------------------------------------------------------------------------------------------
-%        Meter Bathymetry
-% -------------------------------------------------------------------------------------------------------------
-\subsection{Meter bathymetry}
-\label{subsec:DOM_bathy}
-
-Three options are possible for defining the bathymetry, according to the namelist variable \np{nn\_bathy}
-(found in \ngn{namdom} namelist): 
-\begin{description}
-\item[\np{nn\_bathy}\forcode{ = 0}]:
-  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}.
-\item[\np{nn\_bathy}\forcode{ = -1}]:
-  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{nn\_bathy}\forcode{ = 1}]:
-  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 model 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{ln\_isfcav}\forcode{ = .true.}.
-  Defining the ice shelf draft will also define the ice shelf edge and the grounding line position.
-\end{description}
-
-When a global ocean is coupled to an atmospheric model it is better to represent all large water bodies
-(\eg great lakes, Caspian sea...) 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}),
-but the code has to be adapted to the user's configuration.
-
-% -------------------------------------------------------------------------------------------------------------
-%        z-coordinate  and reference coordinate transformation
-% -------------------------------------------------------------------------------------------------------------
-\subsection[$Z$-coordinate (\forcode{ln_zco = .true.}) and ref. coordinate]
-{$Z$-coordinate (\protect\np{ln\_zco}\forcode{ = .true.}) and reference coordinate}
-\label{subsec:DOM_zco}
-
-%>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-\begin{figure}[!tb]
-  \begin{center}
-    \includegraphics[width=\textwidth]{Fig_zgr}
-    \caption{
-      \protect\label{fig:zgr}
-      Default vertical mesh for ORCA2: 30 ocean levels (L30).
-      Vertical level functions for (a) T-point depth and (b) the associated scale factor as computed from
-      \autoref{eq:DOM_zgr_ana_1} using \autoref{eq:DOM_zgr_coef} in $z$-coordinate.
-    }
-  \end{center}
-\end{figure}
-%>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-
-The reference coordinate transformation $z_0(k)$ defines the arrays $gdept_0$ and $gdepw_0$ for $t$- and $w$-points,
-respectively.
-As indicated on \autoref{fig: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 \ngn{namcfg} namelist.
-
-It is possible to define a simple regular vertical grid by giving zero stretching (\np{ppacr}\forcode{ = 0}).
-In that case, the parameters \jp{jpk} (number of $w$-levels) and
-\np{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:DOM_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:zgr}).
-
-If the ice shelf cavities are opened (\np{ln\_isfcav}\forcode{ = .true.}), 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:DOM_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 decrease the self-generated circulation into the ice shelf cavity 
-(which can, in extreme case, leads to blow up).\\
- 
-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:DOM_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:DOM_zgr_ana_2} have been determined such that
-\autoref{eq:DOM_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:zgr} and given in \autoref{tab:orca_zgr}.
-Those values correspond to the parameters \np{ppsur}, \np{ppa0}, \np{ppa1}, \np{ppkth} in \ngn{namcfg} 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}~$=$~\np{ppa0}~$=$~\np{ppa1}~$= 999999$.,
-in \ngn{namcfg} namelist, and specifies instead the four following parameters:
+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} set to \forcode{ =
+.false.} in \ngn{namdom}): 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:z_zps_s_sps}f).  When a linear free surface is assumed
+(\np{ln\_linssh} set to \forcode{ = .true.} in \ngn{namdom}), 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}, \np{ln\_zps}, \np{ln\_sco} and \np{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 \forcode{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} file.
+
+\medskip
+The decision on these choices must be made when the \np{cn\_domcfg} file is constructed.
+Three main choices are offered (\autoref{fig:z_zps_s_sps}a-c):
+
 \begin{itemize}
-\item
-  \np{ppacr}~$= h_{cr}$: stretching factor (nondimensional).
-  The larger \np{ppacr}, the smaller the stretching.
-  Values from $3$ to $10$ are usual.
-\item
-  \np{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}: minimum thickness for the top layer (in meters).
-\item
-  \np{pphmax}: total depth of the ocean (meters).
+\item $z$-coordinate with full step bathymetry (\np{ln\_zco}\forcode{ = .true.}),
+\item $z$-coordinate with partial step ($zps$) bathymetry (\np{ln\_zps}\forcode{ = .true.}),
+\item Generalized, $s$-coordinate (\np{ln\_sco}\forcode{ = .true.}).
 \end{itemize}
-As an example, for the $45$ layers used in the DRAKKAR configuration those parameters are:
-\jp{jpk}~$= 46$, \np{ppacr}~$= 9$, \np{ppkth}~$= 23.563$, \np{ppdzmin}~$= 6~m$, \np{pphmax}~$= 5750~m$.
-
-%>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-\begin{table}
-  \begin{center}
-    \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}
-  \end{center}
-  \caption{
-    \protect\label{tab:orca_zgr}
-    Default vertical mesh in $z$-coordinate for 30 layers ORCA2 configuration as computed from
-    \autoref{eq:DOM_zgr_ana_2} using the coefficients given in \autoref{eq:DOM_zgr_coef}
-  }
-\end{table}
-%>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-
-% -------------------------------------------------------------------------------------------------------------
-%        z-coordinate with partial step
-% -------------------------------------------------------------------------------------------------------------
-\subsection[$Z$-coordinate with partial step (\forcode{ln_zps = .true.})]
-{$Z$-coordinate with partial step (\protect\np{ln\_zps}\forcode{ = .true.})}
-\label{subsec:DOM_zps}
-%--------------------------------------------namdom-------------------------------------------------------
-
-\nlst{namdom} 
-%--------------------------------------------------------------------------------------------------------------
-
-In $z$-coordinate partial step,
-the depths of the model levels are defined by the reference analytical function $z_0(k)$ as described in
-the previous section, \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 \ngn{namdom} namelist,
-as the maximum depth \np{pphmax} in partial steps:
-for example, with \np{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} (thickness in meters, usually $20~m$) or $e_{3t}(jk)*$\np{rn\_e3zps\_rat}
-(a fraction, usually 10\%, of the default thickness $e_{3t}(jk)$).
-
-\gmcomment{ \colorbox{yellow}{Add a figure here of pstep especially at last ocean level }  }
-
-% -------------------------------------------------------------------------------------------------------------
-%        s-coordinate
-% -------------------------------------------------------------------------------------------------------------
-\subsection[$S$-coordinate (\forcode{ln_sco = .true.})]
-{$S$-coordinate (\protect\np{ln\_sco}\forcode{ = .true.})}
-\label{subsec:DOM_sco}
-%------------------------------------------nam_zgr_sco---------------------------------------------------
-%
-%\nlst{namzgr_sco} 
-%--------------------------------------------------------------------------------------------------------------
-Options are defined in \ngn{namzgr\_sco}.
-In $s$-coordinate (\np{ln\_sco}\forcode{ = .true.}), 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:DOM_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:z_zps_s_sps}) or an envelop bathymetry can be defined (\autoref{fig:z_zps_s_sps}).
-The namelist parameter \np{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} and \np{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{ln\_s\_SH94}\forcode{ = .false.} and \np{ln\_s\_SF12}\forcode{ = .false.}).
-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: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:DOM_s}
- \\
-  % \label{eq:DOM_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{ln\_s\_SH94}\forcode{ = .true.}),
-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:SH94_2}
-\]
-
-%>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-\begin{figure}[!ht]
-  \begin{center}
-    \includegraphics[width=\textwidth]{Fig_sco_function}
-    \caption{
-      \protect\label{fig:sco_function}
-      Examples of the stretching function applied to a seamount;
-      from left to right: surface, surface and bottom, and bottom intensified resolutions
-    }
-  \end{center}
-\end{figure}
-%>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-
-where $H_c$ is the critical depth (\np{rn\_hc}) at which the coordinate transitions from pure $\sigma$ to
-the stretched coordinate, and $\theta$ (\np{rn\_theta}) and $b$ (\np{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:sco_function}).
-
-Another example has been provided at version 3.5 (\np{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:z}
-\end{equation}
-
-The function is defined with respect to $\sigma$, the unstretched terrain-following coordinate:
-
-\begin{gather*}
-  % \label{eq:DOM_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:DOM_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}) that stretches towards
-the surface ($\alpha > 1.0$) or the bottom ($\alpha < 1.0$) and
-user prescribed surface (\np{rn\_zs}) and bottom depths.
-The bottom cell depth in this example is given as a function of water depth:
-
-\[
-  % \label{eq:DOM_zb}
-  Z_b = h a + b
-\]
-
-where the namelist parameters \np{rn\_zb\_a} and \np{rn\_zb\_b} are $a$ and $b$ respectively.
-
-%>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-\begin{figure}[!ht]
-  \includegraphics[width=\textwidth]{Fig_DOM_compare_coordinates_surface}
-  \caption{
-    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: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} 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.
-
-% -------------------------------------------------------------------------------------------------------------
-%        z*- or s*-coordinate
-% -------------------------------------------------------------------------------------------------------------
-\subsection[\zstar- or \sstar-coordinate (\forcode{ln_linssh = .false.})]
-{\zstar- or \sstar-coordinate (\protect\np{ln\_linssh}\forcode{ = .false.})}
-\label{subsec:DOM_zgr_star}
-
-This option is described in the Report by Levier \textit{et al.} (2007), available on the \NEMO web site.
-
-%gm% key advantage: minimise the diffusion/dispertion associated with advection in response to high frequency surface disturbances
+
+Additionally, hybrid combinations of the three main coordinates are available:
+$s-z$ or $s-zps$ coordinate (\autoref{fig:z_zps_s_sps}d and \autoref{fig: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} 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{ln\_linssh}\forcode{ = .true.}), \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{Verbatim}[fontsize=\tiny]
+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{Verbatim}
+
+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 \np{bottom\_level} (and, possibly, \np{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 occurr 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 \np{bottom\_level} and \np{top\_level} 2D arrays define the \np{bottom\_level} and top
+wet levels in each grid column. Without ice cavities, \np{top\_level} is essentially a land
+mask (0 on land; 1 everywhere else). With ice cavities, \np{top\_level} determines the
+first wet point below the overlying ice shelf.
+
+
 
 % -------------------------------------------------------------------------------------------------------------
 %        level bathymetry and mask 
 % -------------------------------------------------------------------------------------------------------------
-\subsection{Level bathymetry and mask}
+\subsubsection{Level bathymetry and mask}
 \label{subsec:DOM_msk}
 
-Whatever the vertical coordinate used, the model offers the possibility of representing the bottom topography with
-steps that follow the face of the model cells (step like topography) \citep{madec.delecluse.ea_JPO96}.
-The distribution of the steps in the horizontal is defined in a 2D integer array, mbathy, which
-gives the number of ocean levels (\ie those that are not masked) at each $t$-point.
-mbathy is computed from the meter bathymetry using the definiton of gdept as the number of $t$-points which
-gdept $\leq$ bathy.
-
-Modifications of the model bathymetry are performed in the \textit{bat\_ctl} routine (see \mdl{domzgr} module) after
-mbathy is computed.
-Isolated grid points that do not communicate with another ocean point at the same level are eliminated.
-
-As for the representation of bathymetry, a 2D integer array, misfdep, is created.
-misfdep defines the level of the first wet $t$-point.
-All the cells between $k = 1$ and $misfdep(i,j) - 1$ are masked.
-By default, $misfdep(:,:) = 1$ and no cells are masked.
-
-In case of ice shelf cavities, modifications of the model bathymetry and ice shelf draft into 
-the cavities are performed in the \textit{zgr\_isf} routine.
-The compatibility between ice shelf draft and bathymetry is checked.
-All the locations where the isf cavity is thinnest than \np{rn\_isfhmin} meters are grounded (\ie masked).
-If only one cell on the water column is opened at $t$-, $u$- or $v$-points,
-the bathymetry or the ice shelf draft is dug to fit this constrain.
-If the incompatibility is too strong (need to dig more than 1 cell), the cell is masked.
-
-From the \textit{mbathy} and \textit{misfdep} array, the mask fields are defined as follows:
+
+From \np{top\_level} and \np{bottom\_level} fields, the mask fields are defined as follows:
 \begin{alignat*}{2}
   tmask(i,j,k) &= &  &
     \begin{cases}
-                  0 &\text{if $                  k  <    misfdep(i,j)$} \\
-                  1 &\text{if $misfdep(i,j) \leq k \leq   mbathy(i,j)$} \\
-                  0 &\text{if $                  k  >     mbathy(i,j)$}
+                  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}
   \\
@@ -1010,9 +606,54 @@
 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}).
+%% 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...) 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{Verbatim}[fontsize=\tiny]
+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{Verbatim}
+
+% -------------------------------------------------------------------------------------------------------------
+%        Grid files
+% -------------------------------------------------------------------------------------------------------------
+\subsection{Output grid files}
+\label{subsec:DOM_meshmask}
+
+\nlst{namcfg}
+
+Most of the arrays relating to a particular ocean model configuration dicussed in this
+chapter (grid-point position, scale factors) can be saved in a file if namelist parameter
+\np{ln\_write\_cfg} (namelist \ngn{namcfg}) is set to \forcode{.true.}; the output
+filename is set thorugh parameter \np{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.
+
+\nlst{namdom}
+
+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} (namelist \ngn{namdom}) is set
+to \forcode{.true.}. This file contains additional fields that can be useful for
+post-processing applications
 
 % ================================================================
@@ -1023,22 +664,22 @@
 \label{sec:DTA_tsd}
 %-----------------------------------------namtsd-------------------------------------------
-
 \nlst{namtsd} 
 %------------------------------------------------------------------------------------------
 
-Options are defined in \ngn{namtsd}.
-By default, the ocean start from rest (the velocity field is set to zero) and the initialization of temperature and
-salinity fields is controlled through the \np{ln\_tsd\_ini} namelist parameter.
+Basic initial state options are defined in \ngn{namtsd}.  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} namelist parameter.
+
 \begin{description}
-\item[\np{ln\_tsd\_init}\forcode{ = .true.}]
-  use a T and S input files that can be given on the model grid itself or on their native input data grid.
-  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 relative to the input files are given in the \np{sn\_tem} and \np{sn\_sal} structures.
-  The computation is done in the \mdl{dtatsd} module.
-\item[\np{ln\_tsd\_init}\forcode{ = .false.}]
-  use constant salinity value of $35.5~psu$ and an analytical profile of temperature
-  (typical of the tropical ocean), see \rou{istate\_t\_s} subroutine called from \mdl{istate} module.
+\item[\np{ln\_tsd\_init}\forcode{= .true.}]
+  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} and
+  \np{sn\_sal} structures.  The computation is done in the \mdl{dtatsd} module.
+\item[\np{ln\_tsd\_init}\forcode{= .false.}]
+  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:CFG_gyre}).
 \end{description}
 
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_LDF.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_LDF.tex	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_LDF.tex	(revision 11353)
@@ -23,9 +23,9 @@
 These three aspects of the lateral diffusion are set through namelist parameters
 (see the \ngn{nam\_traldf} and \ngn{nam\_dynldf} below).
-Note that this chapter describes the standard implementation of iso-neutral tracer mixing,
-and Griffies's implementation, which is used if \np{traldf\_grif}\forcode{ = .true.},
-is described in Appdx\autoref{apdx:triad}
-
-%-----------------------------------nam_traldf - nam_dynldf--------------------------------------------
+Note that this chapter describes the standard implementation of iso-neutral tracer mixing. 
+Griffies's implementation, which is used if \np{ln\_traldf\_triad}\forcode{ = .true.},
+is described in \autoref{apdx:triad}
+
+%-----------------------------------namtra_ldf - namdyn_ldf--------------------------------------------
 
 \nlst{namtra_ldf} 
@@ -34,4 +34,31 @@
 %--------------------------------------------------------------------------------------------------------------
 
+% ================================================================
+% Lateral Mixing Operator
+% ================================================================
+\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}, \protect\np{ln\_dynldf\_OFF})}
+
+It is possible to run without explicit lateral diffusion on tracers (\protect\np{ln\_traldf\_OFF}\forcode{ = .true.}) and/or 
+momentum (\protect\np{ln\_dynldf\_OFF}\forcode{ = .true.}). The latter option is even recommended if using the 
+UBS advection scheme on momentum (\np{ln\_dynadv\_ubs}\forcode{ = .true.},
+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}, \protect\np{ln\_dynldf\_lap})}
+Setting \protect\np{ln\_traldf\_lap}\forcode{ = .true.} and/or \protect\np{ln\_dynldf\_lap}\forcode{ = .true.} 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}, \protect\np{ln\_dynldf\_blp})}
+Setting \protect\np{ln\_traldf\_blp}\forcode{ = .true.} and/or \protect\np{ln\_dynldf\_blp}\forcode{ = .true.} 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.
 
 % ================================================================
@@ -88,5 +115,5 @@
 %gm%  caution I'm not sure the simplification was a good idea! 
 
-These slopes are computed once in \rou{ldfslp\_init} when \np{ln\_sco}\forcode{ = .true.}rue,
+These slopes are computed once in \rou{ldf\_slp\_init} when \np{ln\_sco}\forcode{ = .true.},
 and either \np{ln\_traldf\_hor}\forcode{ = .true.} or \np{ln\_dynldf\_hor}\forcode{ = .true.}. 
 
@@ -145,8 +172,8 @@
 \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{traldf\_grif}\forcode{ = .true.};
-  see Appdx \autoref{apdx:triad}).
+  the Griffies scheme is used (\np{ln\_traldf\_triad}\forcode{ = .true.};
+  see \autoref{apdx:triad}).
   In other words, iso-neutral mixing will only be accurately represented with a linear equation of state
-  (\np{nn\_eos}\forcode{ = 1..2}).
+  (\np{ln\_seos}\forcode{ = .true.}).
   In the case of a "true" equation of state, the evaluation of $i$ and $j$ derivatives in \autoref{eq:ldfslp_iso}
   will include a pressure dependent part, leading to the wrong evaluation of the neutral slopes.
@@ -198,10 +225,10 @@
 
 This implementation is a rather old one.
-It is similar to the one proposed by Cox [1987], except for the background horizontal diffusion.
-Indeed, the Cox implementation of isopycnal diffusion in GFDL-type models requires
+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{traldf\_grif\_iso} is set true; see Appdx \autoref{apdx:triad}.
+Griffies's scheme is now available in \NEMO if \np{ln\_traldf\_triad}=\forcode{= .true.}; see \autoref{apdx:triad}.
 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
@@ -242,8 +269,9 @@
 
 For numerical stability reasons \citep{cox_OM87, griffies_bk04}, the slopes must also be bounded by
-$1/100$ everywhere.
+the namelist scalar \np{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.}
 
 %>>>>>>>>>>>>>>>>>>>>>>>>>>>>
@@ -298,63 +326,72 @@
 (see \autoref{sec:LBC_coast}).
 
-
-% ================================================================
-% Lateral Mixing Operator
-% ================================================================
-\section[Lateral mixing operators (\textit{traldf.F90})]
-{Lateral mixing operators (\protect\mdl{traldf}, \protect\mdl{traldf})}
-\label{sec:LDF_op}
-
-
    
 % ================================================================
 % Lateral Mixing Coefficients
 % ================================================================
-\section[Lateral mixing coefficient (\textit{ldftra.F90}, \textit{ldfdyn.F90})]
-{Lateral mixing coefficient (\protect\mdl{ldftra}, \protect\mdl{ldfdyn})}
+\section[Lateral mixing coefficient (\forcode{nn_aht_ijk_t}, \forcode{nn_ahm_ijk_t})]
+{Lateral mixing coefficient (\protect\np{nn\_aht\_ijk\_t}, \protect\np{nn\_ahm\_ijk\_t})}
 \label{sec:LDF_coef}
 
-Introducing a space variation in the lateral eddy mixing coefficients changes the model core memory requirement,
-adding up to four extra three-dimensional arrays for the geopotential or isopycnal second order operator applied to 
-momentum.
-Six CPP keys control the space variation of eddy coefficients: three for momentum and three for tracer.
-The three choices allow:
-a space variation in the three space directions (\key{traldf\_c3d},  \key{dynldf\_c3d}),
-in the horizontal plane (\key{traldf\_c2d},  \key{dynldf\_c2d}),
-or in the vertical only (\key{traldf\_c1d},  \key{dynldf\_c1d}).
-The default option is a constant value over the whole ocean on both momentum and tracers. 
-   
-The number of additional arrays that have to be defined and the gridpoint position at which
-they are defined depend on both the space variation chosen and the type of operator used.
-The resulting eddy viscosity and diffusivity coefficients can be a function of more than one variable.
-Changes in the computer code when switching from one option to another have been minimized by
-introducing the eddy coefficients as statement functions
-(include file \textit{ldftra\_substitute.h90} and \textit{ldfdyn\_substitute.h90}).
-The functions are replaced by their actual meaning during the preprocessing step (CPP).
-The specification of the space variation of the coefficient is made in \mdl{ldftra} and \mdl{ldfdyn},
-or more precisely in include files \textit{traldf\_cNd.h90} and \textit{dynldf\_cNd.h90}, with N=1, 2 or 3.
-The user can modify these include files as he/she wishes.
-The way the mixing coefficient are set in the reference version can be briefly described as follows:
-
-\subsubsection{Constant mixing coefficients (default option)}
-When none of the \key{dynldf\_...} and \key{traldf\_...} keys are defined,
-a constant value is used over the whole ocean for momentum and tracers,
-which is specified through the \np{rn\_ahm0} and \np{rn\_aht0} namelist parameters.
-
-\subsubsection[Vertically varying mixing coefficients (\texttt{\textbf{key\_traldf\_c1d}} and \texttt{\textbf{key\_dynldf\_c1d}})]
-{Vertically varying mixing coefficients (\protect\key{traldf\_c1d} and \key{dynldf\_c1d})}
-The 1D option is only available when using the $z$-coordinate with full step.
-Indeed in all the other types of vertical coordinate,
-the depth is a 3D function of (\textbf{i},\textbf{j},\textbf{k}) and therefore,
-introducing depth-dependent mixing coefficients will require 3D arrays.
-In the 1D option, a hyperbolic variation of the lateral mixing coefficient is introduced in which
-the surface value is \np{rn\_aht0} (\np{rn\_ahm0}), the bottom value is 1/4 of the surface value,
-and the transition takes place around z=300~m with a width of 300~m
-(\ie both the depth and the width of the inflection point are set to 300~m).
-This profile is hard coded in file \textit{traldf\_c1d.h90}, but can be easily modified by users.
-
-\subsubsection[Horizontally varying mixing coefficients (\texttt{\textbf{key\_traldf\_c2d}} and \texttt{\textbf{key\_dynldf\_c2d}})]
-{Horizontally varying mixing coefficients (\protect\key{traldf\_c2d} and \protect\key{dynldf\_c2d})}
-By default the horizontal variation of the eddy coefficient depends on the local mesh size and
+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{nn_aht_ijk_t = -20, -30}, \forcode{nn_ahm_ijk_t = -20,-30})]
+{ Mixing coefficients read from file (\protect\np{nn\_aht\_ijk\_t}\forcode{ = -20, -30}, \protect\np{nn\_ahm\_ijk\_t}\forcode{ = -20, -30})}
+
+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{nn\_aht\_ijk\_t}\forcode{ = -20}, \np{nn\_ahm\_ijk\_t}\forcode{ = -20}) or 3d (\np{nn\_aht\_ijk\_t}\forcode{ = -30},  \np{nn\_ahm\_ijk\_t}\forcode{ = -30}). They must be given at U, V points for tracers and T, F points for momentum (see \autoref{tab:LDF_files}).
+
+%-------------------------------------------------TABLE---------------------------------------------------
+\begin{table}[htb]
+  \begin{center}
+    \begin{tabular}{|l|l|l|l|}
+      \hline
+      Namelist parameter				            & Input filename	                             & dimensions	& variable names                      \\	\hline
+      \np{nn\_ahm\_ijk\_t}\forcode{ = -20}	    & \forcode{eddy_viscosity_2D.nc }            &     $(i,j)$	        & \forcode{ahmt_2d, ahmf_2d}  \\	\hline
+      \np{nn\_aht\_ijk\_t}\forcode{ = -20}           & \forcode{eddy_diffusivity_2D.nc }           &     $(i,j)$	        & \forcode{ahtu_2d, ahtv_2d}    \\	\hline
+      \np{nn\_ahm\_ijk\_t}\forcode{ = -30} 	    & \forcode{eddy_viscosity_3D.nc }            &     $(i,j,k)$	        & \forcode{ahmt_3d, ahmf_3d}  \\	\hline
+      \np{nn\_aht\_ijk\_t}\forcode{ = -30}	    & \forcode{eddy_diffusivity_3D.nc }           &     $(i,j,k)$	        & \forcode{ahtu_3d, ahtv_3d}    \\	\hline
+    \end{tabular}
+    \caption{
+      \protect\label{tab:LDF_files}
+      Description of expected input files if mixing coefficients are read from NetCDF files.
+    }
+  \end{center}
+\end{table}
+%--------------------------------------------------------------------------------------------------------------
+
+\subsection[Constant mixing coefficients (\forcode{nn_aht_ijk_t = 0}, \forcode{nn_ahm_ijk_t = 0})]
+{ Constant mixing coefficients (\protect\np{nn\_aht\_ijk\_t}\forcode{ = 0}, \protect\np{nn\_ahm\_ijk\_t}\forcode{ = 0})}
+
+If constant, mixing coefficients are set thanks to a velocity and a length scales ($U_{scl}$, $L_{scl}$) such that:
+
+\begin{equation}
+  \label{eq: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}, \np{rn\_Uv}, \np{rn\_Ld} and \np{rn\_Lv}.
+
+\subsection[Vertically varying mixing coefficients (\forcode{nn_aht_ijk_t = 10}, \forcode{nn_ahm_ijk_t = 10})]
+{Vertically varying mixing coefficients (\protect\np{nn\_aht\_ijk\_t}\forcode{ = 10}, \protect\np{nn\_ahm\_ijk\_t}\forcode{ = 10})}
+
+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: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{nn_aht_ijk_t = 20}, \forcode{nn_ahm_ijk_t = 20})]
+{Mesh size dependent mixing coefficients (\protect\np{nn\_aht\_ijk\_t}\forcode{ = 20}, \protect\np{nn\_ahm\_ijk\_t}\forcode{ = 20})}
+
+In that case, the horizontal variation of the eddy coefficient depends on the local mesh size and
 the type of operator used:
 \begin{equation}
@@ -362,42 +399,82 @@
   A_l = \left\{
     \begin{aligned}
-      & \frac{\max(e_1,e_2)}{e_{max}} A_o^l  			& \text{for laplacian operator } \\
-      & \frac{\max(e_1,e_2)^{3}}{e_{max}^{3}} A_o^l          & \text{for bilaplacian operator }
+      & \frac{\max(e_1,e_2)}{e_{ref}} A_o^l  			& \text{for laplacian operator } \\
+      & \frac{\max(e_1,e_2)^{3}}{e_{ref}^{3}} A_o^l          & \text{for bilaplacian operator }
     \end{aligned}
   \right.
 \end{equation}
-where $e_{max}$ is the maximum of $e_1$ and $e_2$ taken over the whole masked ocean domain,
-and $A_o^l$ is the \np{rn\_ahm0} (momentum) or \np{rn\_aht0} (tracer) namelist parameter.
+where $e_{ref}$ is a reference grid size harcoded to a $1^{\circ}$ grid size (\ie $e_{ref}\approx 111 km$),
+and $A_o^l$ is the user defined mixing coefficient defined according to  \autoref{eq:constantah}.
 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 increase the range of stability of
-model configurations presenting large changes in grid pacing such as global ocean models.
+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:STP_forward_imp}),
 especially when using a bilaplacian operator.
 
-Other formulations can be introduced by the user for a given configuration.
-For example, in the ORCA2 global ocean model (see Configurations),
-the laplacian viscosity operator uses \np{rn\_ahm0}~= 4.10$^4$ m$^2$/s poleward of 20$^{\circ}$ north and south and
-decreases linearly to \np{rn\_aht0}~= 2.10$^3$ m$^2$/s at the equator \citep{madec.delecluse.ea_JPO96, delecluse.madec_icol99}.
-This modification can be found in routine \rou{ldf\_dyn\_c2d\_orca} defined in \mdl{ldfdyn\_c2d}.
-Similar modified horizontal variations can be found with the Antarctic or Arctic sub-domain options of
-ORCA2 and ORCA05 (see \&namcfg namelist).
-
-\subsubsection[Space varying mixing coefficients (\texttt{\textbf{key\_traldf\_c3d}} and \texttt{\textbf{key\_dynldf\_c3d}})]
-{Space varying mixing coefficients (\protect\key{traldf\_c3d} and \key{dynldf\_c3d})}
-
-The 3D space variation of the mixing coefficient is simply the combination of the 1D and 2D cases,
+\colorbox{yellow}{CASE \np{nn\_aht\_ijk\_t} = 21 to be added}
+
+\subsection[Mesh size and depth dependent mixing coefficients (\forcode{nn_aht_ijk_t = 30}, \forcode{nn_ahm_ijk_t = 30})]
+{Mesh size and depth dependent mixing coefficients (\protect\np{nn\_aht\_ijk\_t}\forcode{ = 30}, \protect\np{nn\_ahm\_ijk\_t}\forcode{ = 30})}
+
+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. 
 
-\subsubsection{Space and time varying mixing coefficients}
-
-There is no default specification of space and time varying mixing coefficient. 
-The only case available is specific to the ORCA2 and ORCA05 global ocean configurations.
-It provides only a tracer mixing coefficient for eddy induced velocity (ORCA2) or both iso-neutral and
-eddy induced velocity (ORCA05) that depends on the local growth rate of baroclinic instability.
-This specification is actually used when an ORCA key and both \key{traldf\_eiv} and \key{traldf\_c2d} are defined.
+\subsection[Velocity dependent mixing coefficients (\forcode{nn_aht_ijk_t = 31}, \forcode{nn_ahm_ijk_t = 31})]
+{Flow dependent mixing coefficients (\protect\np{nn\_aht\_ijk\_t}\forcode{ = 31}, \protect\np{nn\_ahm\_ijk\_t}\forcode{ = 31})}
+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: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{nn\_ahm\_ijk\_t}\forcode{ = 32})}
+
+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: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}), one can deduce the mixing coefficients as follows:
+
+\begin{equation}
+  \label{eq: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:STP_forward_imp}) so that:
+\begin{equation}
+  \label{eq: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} and \np{rn\_maxfac} respectively.
+
+\subsection{About space and time varying mixing coefficients}
 
 The following points are relevant when the eddy coefficient varies spatially:
@@ -412,31 +489,18 @@
 (\autoref{sec:dynldf_properties}).
 
-(3) for isopycnal diffusion on momentum or tracers, an additional purely horizontal background diffusion with
-uniform coefficient can be added by setting a non zero value of \np{rn\_ahmb0} or \np{rn\_ahtb0},
-a background horizontal eddy viscosity or diffusivity coefficient
-(namelist parameters whose default values are $0$).
-However, the technique used to compute the isopycnal slopes is intended to get rid of such a background diffusion,
-since it introduces spurious diapycnal diffusion (see \autoref{sec:LDF_slp}).
-
-(4) when an eddy induced advection term is used (\key{traldf\_eiv}),
-$A^{eiv}$, the eddy induced coefficient has to be defined.
-Its space variations are controlled by the same CPP variable as for the eddy diffusivity coefficient
-(\ie \key{traldf\_cNd}). 
-
-(5) the eddy coefficient associated with a biharmonic operator must be set to a \emph{negative} value.
-
-(6) it is possible to use both the laplacian and biharmonic operators concurrently.
-
-(7) it is possible to run without explicit lateral diffusion on momentum
-(\np{ln\_dynldf\_lap}\forcode{ = .?.}\np{ln\_dynldf\_bilap}\forcode{ = .false.}).
-This is recommended when using the UBS advection scheme on momentum (\np{ln\_dynadv\_ubs}\forcode{ = .true.},
-see \autoref{subsec:DYN_adv_ubs}) and can be useful for testing purposes.
-
 % ================================================================
 % Eddy Induced Mixing
 % ================================================================
-\section[Eddy induced velocity (\textit{traadv\_eiv.F90}, \textit{ldfeiv.F90})]
-{Eddy induced velocity (\protect\mdl{traadv\_eiv}, \protect\mdl{ldfeiv})}
+\section[Eddy induced velocity (\forcode{ln_ldfeiv = .true.})]
+{Eddy induced velocity (\protect\np{ln\_ldfeiv}\forcode{ = .true.})}
+
 \label{sec:LDF_eiv}
+
+%--------------------------------------------namtra_eiv---------------------------------------------------
+
+\nlst{namtra_eiv}
+
+%--------------------------------------------------------------------------------------------------------------
+
 
 %%gm  from Triad appendix  : to be incorporated....
@@ -460,5 +524,5 @@
 }
 
-When Gent and McWilliams [1990] diffusion is used (\key{traldf\_eiv} defined),
+When  \citet{gent.mcwilliams_JPO90} diffusion is used (\np{ln\_ldfeiv}\forcode{ = .true.}),
 an eddy induced tracer advection term is added,
 the formulation of which depends on the slopes of iso-neutral surfaces.
@@ -466,5 +530,6 @@
 \ie \autoref{eq:ldfslp_geo} is used in $z$-coordinates,
 and the sum \autoref{eq:ldfslp_geo} + \autoref{eq:ldfslp_iso} in $s$-coordinates.
-The eddy induced velocity is given by: 
+
+If isopycnal mixing is used in the standard way, \ie \np{ln\_traldf\_triad}\forcode{ = .false.}, the eddy induced velocity is given by: 
 \begin{equation}
   \label{eq:ldfeiv}
@@ -475,8 +540,7 @@
   \end{split}
 \end{equation}
-where $A^{eiv}$ is the eddy induced velocity coefficient whose value is set through \np{rn\_aeiv},
-a \textit{nam\_traldf} namelist parameter.
-The three components of the eddy induced velocity are computed and
-add to the eulerian velocity in \mdl{traadv\_eiv}.
+where $A^{eiv}$ is the eddy induced velocity coefficient whose value is set through \np{nn\_aei\_ijk\_t} \ngn{namtra\_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
@@ -488,4 +552,26 @@
 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}, \np{rn\_Ue}, \np{rn\_Le} namelist parameters). 
+\colorbox{yellow}{CASE \np{nn\_aei\_ijk\_t} = 21 to be added}
+
+In case of setting \np{ln\_traldf\_triad}\forcode{ = .true.}, a skew form of the eddy induced advective fluxes is used, which is described in \autoref{apdx:triad}.
+
+% ================================================================
+% Mixed layer eddies
+% ================================================================
+\section[Mixed layer eddies (\forcode{ln_mle = .true.})]
+{Mixed layer eddies (\protect\np{ln\_mle}\forcode{ = .true.})}
+
+\label{sec:LDF_mle}
+
+%--------------------------------------------namtra_eiv---------------------------------------------------
+
+\nlst{namtra_mle}
+
+%--------------------------------------------------------------------------------------------------------------
+
+If  \np{ln\_mle}\forcode{ = .true.} in \ngn{namtra\_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}
 
 \biblio
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_OBS.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_OBS.tex	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_OBS.tex	(revision 11353)
@@ -8,19 +8,29 @@
 \label{chap:OBS}
 
-Authors: D. Lea, M. Martin, K. Mogensen, A. Vidard, A. Weaver, A. Ryan, ...   % do we keep that ?
-
 \minitoc
 
+\vfill
+\begin{figure}[b]
+\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}
+\end{figure}
+
 \newpage
 
-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 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 timestep.
-The code is then called again after each timestep from \mdl{step}.
-The code is only activated if the namelist logical \np{ln\_diaobs} is set to true.
+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 \ngn{namobs} namelist logical \np{ln\_diaobs} is set to true.
 
 For all data types a 2D horizontal interpolator or averager is needed to
@@ -28,5 +38,5 @@
 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. 
+This now works in a generalised vertical coordinate system.
 
 Some profile observation types (\eg tropical moored buoys) are made available as daily averaged quantities.
@@ -36,17 +46,17 @@
 the observation operator code can calculate equivalent night-time average model SST fields by
 setting the namelist value \np{ln\_sstnight} to true.
-Otherwise the model value from the nearest timestep to the observation time is used.
-
-The code is controlled by the namelist \textit{namobs}.
+Otherwise (by default) the model value from the nearest time step to the observation time is used.
+
+The code is controlled by the namelist \ngn{namobs}.
 See the following sections for more details on setting up the namelist.
 
-\autoref{sec:OBS_example} introduces a test example of the observation operator code including
+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.
-\autoref{sec:OBS_details} introduces some more technical details of the different observation types used and
-also shows a more complete namelist.
-\autoref{sec:OBS_theory} introduces some of the theoretical aspects of the observation operator including
+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.
-\autoref{sec:OBS_ooo} describes the offline observation operator code.
-\autoref{sec:OBS_obsutils} introduces some utilities to help working with the files produced by the OBS code.
+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.
 
 % ================================================================
@@ -56,7 +66,7 @@
 \label{sec:OBS_example}
 
-This section describes an example of running the observation operator code using
-profile data which can be freely downloaded.
-It shows how to adapt an existing run and build of NEMO to run the observation operator.
+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 \np{ORCA2\_ICE\_OBS} SETTE test.
 
 \begin{enumerate}
@@ -65,17 +75,19 @@
 \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 using: 
+  the observation operator compares the model and observations for a matching date and time.
+
+\item Compile the OBSTOOLS code in the \np{tools} directory using:
 \begin{cmds}
-./maketools -n OBSTOOLS -m [ARCH].
+./maketools -n OBSTOOLS -m [ARCH]
 \end{cmds}
 
-\item Convert the EN4 data into feedback format: 
+replacing \np{[ARCH]} with the build architecture file for your machine. Note the tools are checked out from a separate repository under \np{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:
+\item Include the following in the \NEMO namelist to run the observation operator on this data:
 \end{enumerate}
 
@@ -87,15 +99,15 @@
 This can be expensive, particularly for large numbers of observations,
 setting \np{ln\_grid\_search\_lookup} allows the use of a lookup table which
-is saved into an ``xypos`` file (or files).
+is saved into an \np{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} means that the code distributes the observations evenly between processors.
 Alternatively each processor will work with observations located within the model subdomain
-(see section~\autoref{subsec:OBS_parallel}).
+(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 section~\autoref{sec:OBS_obsutils}.
-Utilites to convert other input data formats into the feedback format are also described in
-section~\autoref{sec:OBS_obsutils}.
+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)}
@@ -110,10 +122,10 @@
 %-------------------------------------------------------------------------------------------------------------
 
-The observation operator code uses the "feedback" observation file format for all data types.
+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}
+\subsection{Profile feedback file}
 
 \begin{clines}
@@ -271,5 +283,5 @@
 \end{clines}
 
-\subsection{Sea level anomaly feedback}
+\subsection{Sea level anomaly feedback file}
 
 \begin{clines}
@@ -395,5 +407,5 @@
 \end{clines}
 
-The mean dynamic topography (MDT) must be provided in a separate file defined on
+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.
@@ -417,5 +429,5 @@
 \end{clines}
 
-\subsection{Sea surface temperature feedback}
+\subsection{Sea surface temperature feedback file}
 
 \begin{clines}
@@ -546,6 +558,6 @@
 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). 
+\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}.
@@ -559,13 +571,13 @@
 \item \np{nn\_2dint}\forcode{ = 4}: Polynomial interpolation
 \item \np{nn\_2dint}\forcode{ = 5}: Radial footprint averaging with diameter specified in the namelist as
-  \np{rn\_???\_avglamscl} in degrees or metres (set using \np{ln\_???\_fp\_indegs})
+  \np{rn\_[var]\_avglamscl} in degrees or metres (set using \np{ln\_[var]\_fp\_indegs})
 \item \np{nn\_2dint}\forcode{ = 6}: Rectangular footprint averaging with E/W and N/S size specified in
-  the namelist as \np{rn\_???\_avglamscl} and \np{rn\_???\_avgphiscl} in degrees or metres
-  (set using \np{ln\_???\_fp\_indegs})
+  the namelist as \np{rn\_[var]\_avglamscl} and \np{rn\_[var]\_avgphiscl} in degrees or metres
+  (set using \np{ln\_[var]\_fp\_indegs})
 \end{itemize}
-The ??? in the last two options indicate these options should be specified for each observation type for
+Replace \np{[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} default option can be overridden for surface observation types using
-namelist values \np{nn\_2dint\_???} where ??? is one of sla,sst,sss,sic.
+namelist values \np{nn\_2dint\_[var]} where \np{[var]} is the observation type.
 
 Below is some more detail on the various options for interpolation and averaging available in NEMO.
@@ -573,16 +585,18 @@
 \subsubsection{Horizontal interpolation}
 
-Consider an observation point ${\mathrm P}$ with with longitude and latitude $({\lambda_{}}_{\mathrm P}, \phi_{\mathrm P})$ and
+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
+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} & \hspace{-2mm} = \hspace{-2mm} &
-                                                   \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)
+  {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}$.
@@ -597,47 +611,52 @@
   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{align*}
+
+  \begin{alignat*}{2}
     {w_{}}_{\mathrm A} = s({\mathrm P}, {\mathrm B}) \, s({\mathrm P}, {\mathrm C}) \, s({\mathrm P}, {\mathrm D})
-  \end{align*}
-  where 
-  \begin{align*}
-    s\left ({\mathrm P}, {\mathrm M} \right ) 
-     & \hspace{-2mm} = \hspace{-2mm} & 
-      \cos^{-1} \! \left\{ 
+  \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}) 
+             + \cos {\phi_{}}_{\mathrm P} \cos {\phi_{}}_{\mathrm M}
+               \cos ({\lambda_{}}_{\mathrm M} - {\lambda_{}}_{\mathrm P})
                    \right\}
-   \end{align*}
+   \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{align*}
-     s\left( {\mathrm P}, {\mathrm M} \right) & \hspace{-2mm} = \hspace{-2mm} & \sin^{-1} \! \left\{ \sqrt{ 1 - x^2 } \right\}
-   \end{align*}
+
+   \begin{alignat*}{2}
+     s\left( {\mathrm P}, {\mathrm M} \right) = \sin^{-1} \! \left\{ \sqrt{ 1 - x^2 } \right\}
+   \end{alignat*}
+
    where
-   \begin{align*}
-     x & \hspace{-2mm} = \hspace{-2mm} &
-                                         {a_{}}_{\mathrm M} {a_{}}_{\mathrm P} + {b_{}}_{\mathrm M} {b_{}}_{\mathrm P} + {c_{}}_{\mathrm M} {c_{}}_{\mathrm P}
-   \end{align*}
-   and 
-   \begin{align*}
-      {a_{}}_{\mathrm M} & \hspace{-2mm} = \hspace{-2mm} & \sin {\phi_{}}_{\mathrm M}, \\
-      {a_{}}_{\mathrm P} & \hspace{-2mm} = \hspace{-2mm} & \sin {\phi_{}}_{\mathrm P}, \\
-      {b_{}}_{\mathrm M} & \hspace{-2mm} = \hspace{-2mm} & \cos {\phi_{}}_{\mathrm M} \cos {\phi_{}}_{\mathrm M}, \\
-      {b_{}}_{\mathrm P} & \hspace{-2mm} = \hspace{-2mm} & \cos {\phi_{}}_{\mathrm P} \cos {\phi_{}}_{\mathrm P}, \\
-      {c_{}}_{\mathrm M} & \hspace{-2mm} = \hspace{-2mm} & \cos {\phi_{}}_{\mathrm M} \sin {\phi_{}}_{\mathrm M}, \\
-      {c_{}}_{\mathrm P} & \hspace{-2mm} = \hspace{-2mm} & \cos {\phi_{}}_{\mathrm P} \sin {\phi_{}}_{\mathrm P}.
-  \end{align*}
+
+   \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[2.] {\bfseries Great-Circle distance-weighted interpolation with small angle approximation.}
   Similar to the previous interpolation but with the distance $s$ computed as
-  \begin{align*}
+  \begin{alignat*}{2}
     s\left( {\mathrm P}, {\mathrm M} \right)
-    & \hspace{-2mm} = \hspace{-2mm} &
-                                      \sqrt{ \left( {\phi_{}}_{\mathrm M} - {\phi_{}}_{\mathrm P} \right)^{2}
+    & = & \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{align*}
+  \end{alignat*}
   where $M$ corresponds to $A$, $B$, $C$ or $D$.
 
@@ -649,5 +668,5 @@
   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}
 
@@ -658,8 +677,7 @@
 \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 is calculated in the local grid domain for which
-  the averaging is likely need to cover.
-\item The lats/longs of the grid points surrounding the nearest model grid box are extracted using
-  existing mpi routines.
+\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.
@@ -673,5 +691,5 @@
 
 Examples of the weights calculated for an observation with rectangular and radial footprints are shown in
-Figs.~\autoref{fig:obsavgrec} and~\autoref{fig:obsavgrad}.
+\autoref{fig:obsavgrec} and~\autoref{fig:obsavgrad}.
 
 %>>>>>>>>>>>>>>>>>>>>>>>>>>>>
@@ -696,5 +714,5 @@
       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.
-    } 
+    }
   \end{center}
 \end{figure}
@@ -704,15 +722,15 @@
 \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.
+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 
+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. 
+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 
+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}
@@ -750,5 +768,5 @@
 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. 
+the $i$ and $j$ ranges of this point searched to determine the precise four points surrounding the observation.
 
 \subsection{Parallel aspects of horizontal interpolation}
@@ -757,10 +775,9 @@
 For horizontal interpolation, there is the basic problem that
 the observations are unevenly distributed on the globe.
-In numerical models, it is common to divide the model grid into subgrids (or domains) where
+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.
-This approach is used by \NEMO.
-
-For observations there is no natural distribution since the observations are not equally distributed on the globe. 
+
+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;
@@ -784,10 +801,10 @@
 the domain of the grid-point parallelization.
 \autoref{fig:obslocal} 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. 
+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.
-Of course, this is under the assumption that we are only using a $2 \times 2$ grid-point stencil for
+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.
@@ -827,87 +844,70 @@
 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.
+
 \newpage
 
 % ================================================================
-% Offline observation operator documentation
+% Standalone observation operator documentation
 % ================================================================
 
 %\usepackage{framed}
 
-\section{Offline observation operator}
-\label{sec:OBS_ooo}
+\section{Standalone observation operator}
+\label{sec:OBS_sao}
 
 \subsection{Concept}
 
-The obs oper maps model variables to observation space.
-It is possible to apply this mapping without running the model.
-The software which performs this functionality is known as the \textbf{offline obs oper}.
-The obs oper is divided into three stages.
-An initialisation phase, an interpolation phase and an output phase.
-The implementation of which is outlined in the previous sections.
-During the interpolation phase the offline obs oper populates the model arrays by
-reading saved model fields from disk.
-
-There are two ways of exploiting this offline capacity.
+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 obs oper.
-The second is to take advantage of the offline setting in which
-multiple model counterparts can be calculated 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, I mean any method which produces an estimate of physical reality which is not an observed value.
-In the case of class 4 files this means forecasts, analyses, persisted analyses and
-climatological values verifying at the same time.
-Although the class 4 file format doesn't account for multiple ensemble members or
-multiple experiments per observation, it is possible to include these components in the same or multiple files.
+By forecast, we mean any method which produces an estimate of physical reality which is not an observed value.
 
 %--------------------------------------------------------------------------------------------------------
-% offline_oper.exe 
+% sao.exe
 %--------------------------------------------------------------------------------------------------------
 
-\subsection{Using the offline observation operator}
+\subsection{Using the standalone observation operator}
 
 \subsubsection{Building}
 
-In addition to \emph{OPA\_SRC} the offline obs oper requires the inclusion of the \emph{OOO\_SRC} directory.
-\emph{OOO\_SRC} contains a replacement \mdl{nemo} and \mdl{nemogcm} which
+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}.
-This is the approach taken by \emph{SAS\_SRC} and \emph{OFF\_SRC}.
+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 
+% Running
 %--------------------------------------------------------------------------------------------------------
 \subsubsection{Running}
 
-The simplest way to use the executable is to edit and append the \textbf{ooo.nml} namelist to
-a full NEMO namelist and then to run the executable as if it were nemo.exe. 
-
-\subsubsection{Quick script}
-
-A useful Python utility to control the namelist options can be found in \textbf{OBSTOOLS/OOO}.
-The functions which locate model fields and observation files can be manually specified.
-The package can be installed by appropriate use of the included setup.py script.
-
-Documentation can be auto-generated by Sphinx by running \emph{make html} in the \textbf{doc} directory.
+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 offline observation operator}
-The observation files and settings understood by \textbf{namobs} have been outlined in the online obs oper section.
-In addition there are two further namelists wich control the operation of the offline obs oper.
-\textbf{namooo} which controls the input model fields and \textbf{namcl4} which
-controls the production of class 4 files. 
+\subsection{Configuring the standalone observation operator}
+The observation files and settings understood by \ngn{namobs} have been outlined in the online observation operator section.
+In addition is a further namelist \ngn{namsao} which used to set the input model fields for the SAO
 
 \subsubsection{Single field}
 
-In offline mode 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. 
+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 \textbf{namooo} namelist specifying
+For each field read there must be an entry in the \ngn{namsao} 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.
@@ -915,11 +915,11 @@
 \begin{forlines}
 !----------------------------------------------------------------------
-!       namooo Offline obs_oper namelist
+!       namsao Standalone obs_oper namelist
 !----------------------------------------------------------------------
-!   ooo_files    specifies the files containing the model counterpart
-!   nn_ooo_idx   specifies the time_counter index within the model file
-&namooo
-   ooo_files = "foo.nc"
-   nn_ooo_idx = 2
+!   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}
@@ -927,5 +927,5 @@
 \subsubsection{Multiple fields per run}
 
-Model field iteration is controlled via \textbf{nn\_ooo\_freq} which
+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.
@@ -933,13 +933,13 @@
 \begin{forlines}
 !----------------------------------------------------------------------
-!       namooo Offline obs_oper namelist
+!       namsao Standalone obs_oper namelist
 !----------------------------------------------------------------------
-!   ooo_files    specifies the files containing the model counterpart
-!   nn_ooo_idx   specifies the time_counter index within the model file
-!   nn_ooo_freq  specifies number of time steps between read operations
-&namooo
-   ooo_files = "foo.nc" "foo.nc"
-   nn_ooo_idx = 1 2
-   nn_ooo_freq = 144
+!   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}
@@ -952,208 +952,11 @@
 %\end{framed}
 
-It is easy to see how a collection of fields taken fron a number of files at different indices can be combined at
+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.
-As long as all that is needed is a single model counterpart at a regular interval then
-namooo is all that needs to be edited.
-However, a far more interesting approach can be taken in which multiple forecasts, analyses, persisted analyses and
-climatologies are considered against the same set of observations.
-For this a slightly more complicated approach is needed.
-It is referred to as \emph{Class 4} since it is the fourth metric defined by the GODAE intercomparison project.
-
-%--------------------------------------------------------------------------------------------------------
-% Class 4 file section
-%--------------------------------------------------------------------------------------------------------
-\subsubsection{Multiple model counterparts per observation a.k.a Class 4}
-
-A generalisation of feedback files to allow multiple model components per observation.
-For a single observation, as well as previous forecasts verifying at the same time
-there are also analyses, persisted analyses and climatologies. 
-
-
-The above namelist performs two basic functions.
-It organises the fields given in \textbf{namooo} into groups so that observations can be matched up multiple times.
-It also controls the metadata and the output variable of the class 4 file when a write routine is called.
-
-%\begin{framed}
-\textbf{Note: ln\_cl4} must be set to \forcode{.true.} in \textbf{namobs} to use class 4 outputs.
-%\end{framed}
-
-\subsubsection{Class 4 naming convention}
-
-The standard class 4 file naming convention is as follows.
-
-\noindent
-\linebreak
-\textbf{\$\{prefix\}\_\$\{yyyymmdd\}\_\$\{sys\}\_\$\{cfg\}\_\$\{vn\}\_\$\{kind\}\_\$\{nproc\}}.nc
-
-\noindent
-\linebreak
-Much of the namelist is devoted to specifying this convention.
-The following namelist settings control the elements of the output file names.
-Each should be specified as a single string of character data.
-
-\begin{description}
-\item[cl4\_prefix]
-  Prefix for class 4 files \eg class4
-\item[cl4\_date]
-  YYYYMMDD validity date
-\item[cl4\_sys]
-  The name of the class 4 model system \eg FOAM
-\item[cl4\_cfg]
-  The name of the class 4 model configuration \eg orca025
-\item[cl4\_vn]
-  The name of the class 4 model version \eg 12.0
-\end{description}
-
-\noindent
-The kind is specified by the observation type internally to the obs oper.
-The processor number is specified internally in NEMO. 
-
-\subsubsection{Class 4 file global attributes}
-
-Global attributes necessary to fulfill the class 4 file definition.
-These are also useful pieces of information when collaborating with external partners.
-
-\begin{description}
-\item[cl4\_contact]
-  Contact email for class 4 files.
-\item[cl4\_inst]
-  The name of the producers institution.
-\item[cl4\_cfg]
-  The name of the class 4 model configuration \eg orca025
-\item[cl4\_vn]
-  The name of the class 4 model version \eg 12.0
-\end{description}
-
-\noindent
-The obs\_type, creation date and validity time are specified internally to the obs oper.
-
-\subsubsection{Class 4 model counterpart configuration}
-
-As seen previously it is possible to perform a single sweep of the obs oper and
-specify a collection of model fields equally spaced along that sweep.
-In the class 4 case the single sweep is replaced with multiple sweeps and
-a certain ammount of book keeping is needed to ensure each model counterpart makes its way to
-the correct piece of memory in the output files.
-
-\noindent
-\linebreak
-In terms of book keeping, the offline obs oper needs to know how many full sweeps need to be performed.
-This is specified via the \textbf{cl4\_match\_len} variable and
-is the total number of model counterparts per observation.
-For example, a 3 forecasts plus 3 persistence fields plus an analysis field would be 7 counterparts per observation.
-
-\begin{forlines}
-   cl4_match_len = 7
-\end{forlines}
-
-Then to correctly allocate a class 4 file the forecast axis must be defined.
-This is controlled via \textbf{cl4\_fcst\_len}, which in out above example would be 3.
-
-\begin{forlines}
-   cl4_fcst_len = 3
-\end{forlines}
-
-Then for each model field it is necessary to designate what class 4 variable and index along
-the forecast dimension the model counterpart should be stored in the output file.
-As well as a value for that lead time in hours, this will be useful when interpreting the data afterwards. 
-
-\begin{forlines}
-   cl4_vars = "forecast" "forecast" "forecast" "persistence" "persistence"
-              "persistence" "best_estimate"
-   cl4_fcst_idx = 1 2 3 1 2 3 1
-   cl4_leadtime = 12 36 60 
-\end{forlines}
-
-In terms of files and indices of fields inside each file the class 4 approach makes use of
-the \textbf{namooo} namelist.
-If our fields are in separate files with a single field per file our example inputs will be specified.
-
-\begin{forlines}
-   ooo_files = "F.1.nc" "F.2.nc" "F.3.nc" "P.1.nc" "P.2.nc" "P.3.nc" "A.1.nc"
-   nn_ooo_idx = 1 1 1 1 1 1 1
-\end{forlines}
-
-When we combine all of the naming conventions, global attributes and i/o instructions the class 4 namelist becomes.
-
-\begin{forlines}
-!----------------------------------------------------------------------
-!       namooo Offline obs_oper namelist
-!----------------------------------------------------------------------
-!   ooo_files    specifies the files containing the model counterpart
-!   nn_ooo_idx   specifies the time_counter index within the model file
-!   nn_ooo_freq  specifies number of time steps between read operations
-&namooo
-   ooo_files = "F.1.nc" "F.2.nc" "F.3.nc" "P.1.nc" "P.2.nc" "P.3.nc" "A.1.nc"
-   nn_ooo_idx = 1 1 1 1 1 1 1
-/
-!----------------------------------------------------------------------
-!       namcl4 Offline obs_oper class 4 namelist
-!----------------------------------------------------------------------
-!
-!  Naming convention
-!  -----------------
-!  cl4_prefix    specifies the output file prefix
-!  cl4_date      specifies the output file validity date
-!  cl4_sys       specifies the model counterpart system
-!  cl4_cfg       specifies the model counterpart configuration
-!  cl4_vn        specifies the model counterpart version
-!  cl4_inst      specifies the model counterpart institute
-!  cl4_contact   specifies the file producers contact details
-!
-!  I/O specification
-!  -----------------
-!  cl4_vars      specifies the names of the output file netcdf variable
-!  cl4_fcst_idx  specifies output file forecast index
-!  cl4_fcst_len  specifies forecast axis length
-!  cl4_match_len specifies number of unique matches per observation
-!  cl4_leadtime  specifies the forecast axis lead time 
-!
-&namcl4
-   cl4_match_len = 7
-   cl4_fcst_len = 3
-   cl4_fcst_idx = 1 2 3 1 2 3 1
-   cl4_vars = "forecast" "forecast" "forecast" "persistence" "persistence"
-              "persistence" "best_estimate"
-   cl4_leadtime = 12 36 60
-   cl4_prefix = "class4"
-   cl4_date = "20130101"
-   cl4_vn = "12.0"
-   cl4_sys = "FOAM"
-   cl4_cfg = "AMM7"
-   cl4_contact = "example@example.com"
-   cl4_inst = "UK Met Office"
-/
-\end{forlines}
-
-\subsubsection{Climatology interpolation}
-
-The climatological counterpart is generated at the start of the run by
-restarting the model from climatology through appropriate use of \textbf{namtsd}.
-To override the offline observation operator read routine and to take advantage of the restart settings,
-specify the first entry in \textbf{cl4\_vars} as "climatology".
-This will then pipe the restart from climatology into the output class 4 file.
-As in every other class 4 matchup the input file, input index and output index must be specified.
-These can be replaced with dummy data since they are not used but
-they must be present to cycle through the matchups correctly. 
-
-\subsection{Advanced usage}
-
-In certain cases it may be desirable to include both multiple model fields per observation window with
-multiple match ups per observation.
-This can be achieved by specifying \textbf{nn\_ooo\_freq} as well as the class 4 settings.
-Care must be taken in generating the ooo\_files list such that the files are arranged into
-consecutive blocks of single match ups.
-For example, 2 forecast fields of 12 hourly data would result in 4 separate read operations but
-only 2 write operations, 1 per forecast.
-
-\begin{forlines}
-   ooo_files = "F1.nc" "F1.nc" "F2.nc" "F2.nc"
-...
-   cl4_fcst_idx = 1 2
-\end{forlines}
-
-The above notation reveals the internal split between match up iterators and file iterators.
-This technique has not been used before so experimentation is needed before results can be trusted.
+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.
 
 \newpage
@@ -1162,10 +965,10 @@
 \label{sec:OBS_obsutils}
 
-Some tools for viewing and processing of observation and feedback files are provided in
-the NEMO repository for convenience.
-These include OBSTOOLS which are a collection of \fortran programs which are helpful to deal with feedback files.
+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 tool is an IDL program called dataplot which uses a graphical interface to
+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.
@@ -1173,26 +976,12 @@
 \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 NEMO observation operator.
-The utilities are as follows
-
-\subsubsection{c4comb}
-
-The program c4comb combines multiple class 4 files produced by individual processors in
-an MPI run of NEMO offline obs\_oper into a single class 4 file.
-The program is called in the following way:
-
-
-\footnotesize
-\begin{cmds}
-c4comb.exe outputfile inputfile1 inputfile2 ...
-\end{cmds}
+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.
-The program is called in the following way:
-
-\footnotesize
+It is called in the following way:
+
 \begin{cmds}
 corio2fb.exe outputfile inputfile1 inputfile2 ...
@@ -1202,7 +991,6 @@
 
 The program enact2fb converts profile observation files from the ENACT format to the standard feedback format.
-The program is called in the following way:
-
-\footnotesize
+It is called in the following way:
+
 \begin{cmds}
 enact2fb.exe outputfile inputfile1 inputfile2 ...
@@ -1212,8 +1000,7 @@
 
 The program fbcomb combines multiple feedback files produced by individual processors in
-an MPI run of NEMO into a single feedback file.
-The program is called in the following way:
-
-\footnotesize
+an MPI run of \NEMO into a single feedback file.
+It is called in the following way:
+
 \begin{cmds}
 fbcomb.exe outputfile inputfile1 inputfile2 ...
@@ -1223,7 +1010,6 @@
 
 The program fbmatchup will match observations from two feedback files.
-The program is called in the following way:
-
-\footnotesize
+It is called in the following way:
+
 \begin{cmds}
 fbmatchup.exe outputfile inputfile1 varname1 inputfile2 varname2 ...
@@ -1234,7 +1020,6 @@
 The program fbprint will print the contents of a feedback file or files to standard output.
 Selected information can be output using optional arguments.
-The program is called in the following way:
-
-\footnotesize
+It is called in the following way:
+
 \begin{cmds}
 fbprint.exe [options] inputfile
@@ -1246,11 +1031,11 @@
      -B            Select observations based on QC flags
      -u            unsorted
-     -s ID         select station ID  
+     -s ID         select station ID
      -t TYPE       select observation type
-     -v NUM1-NUM2  select variable range to print by number 
+     -v NUM1-NUM2  select variable range to print by number
                       (default all)
-     -a NUM1-NUM2  select additional variable range to print by number 
+     -a NUM1-NUM2  select additional variable range to print by number
                       (default all)
-     -e NUM1-NUM2  select extra variable range to print by number 
+     -e NUM1-NUM2  select extra variable range to print by number
                       (default all)
      -d            output date range
@@ -1262,7 +1047,6 @@
 
 The program fbsel will select or subsample observations.
-The program is called in the following way:
-
-\footnotesize
+It is called in the following way:
+
 \begin{cmds}
 fbsel.exe <input filename> <output filename>
@@ -1272,7 +1056,6 @@
 
 The program fbstat will output summary statistics in different global areas into a number of files.
-The program is called in the following way:
-
-\footnotesize
+It is called in the following way:
+
 \begin{cmds}
 fbstat.exe [-nmlev] <filenames>
@@ -1283,7 +1066,6 @@
 The program fbthin will thin the data to 1 degree resolution.
 The code could easily be modified to thin to a different resolution.
-The program is called in the following way:
-
-\footnotesize
+It is called in the following way:
+
 \begin{cmds}
 fbthin.exe inputfile outputfile
@@ -1293,7 +1075,6 @@
 
 The program sla2fb will convert an AVISO SLA format file to feedback format.
-The program is called in the following way:
-
-\footnotesize
+It is called in the following way:
+
 \begin{cmds}
 sla2fb.exe [-s type] outputfile inputfile1 inputfile2 ...
@@ -1306,7 +1087,6 @@
 
 The program vel2fb will convert TAO/PIRATA/RAMA currents files to feedback format.
-The program is called in the following way:
-
-\footnotesize
+It is called in the following way:
+
 \begin{cmds}
 vel2fb.exe outputfile inputfile1 inputfile2 ...
@@ -1320,8 +1100,9 @@
 
 An IDL program called dataplot is included which uses a graphical interface to
-visualise observations and feedback files.
+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:
-\footnotesize
+
 \begin{minted}{idl}
 IDL> dataplot, "filename"
@@ -1331,5 +1112,5 @@
 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.
-\footnotesize
+
 \begin{minted}{idl}
 IDL> spawn, 'ls profb*.nc', files
@@ -1350,5 +1131,5 @@
 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.
+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.
@@ -1362,5 +1143,5 @@
 observation minus background value.
 The next group of radio buttons selects the map projection.
-This can either be regular latitude longitude grid, or north or south polar stereographic.
+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.
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_SBC.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_SBC.tex	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_SBC.tex	(revision 11353)
@@ -2,8 +2,9 @@
 
 \begin{document}
-% ================================================================
-% Chapter —— Surface Boundary Condition (SBC, ISF, ICB) 
-% ================================================================
-\chapter{Surface Boundary Condition (SBC, ISF, ICB)}
+
+% ================================================================
+% Chapter —— Surface Boundary Condition (SBC, SAS, ISF, ICB) 
+% ================================================================
+\chapter{Surface Boundary Condition (SBC, SAS, ISF, ICB)}
 \label{chap:SBC}
 \minitoc
@@ -16,5 +17,6 @@
 %--------------------------------------------------------------------------------------------------------------
 
-The ocean needs six fields as surface boundary condition:
+The ocean needs seven fields as surface boundary condition:
+
 \begin{itemize}
 \item
@@ -26,66 +28,85 @@
 \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}
-plus an optional field:
+
+Four different ways are available to provide the seven fields to the ocean. They are controlled by
+namelist \ngn{namsbc} variables:
+
 \begin{itemize}
-	\item the atmospheric pressure at the ocean surface $\left( p_a \right)$
+\item
+  a bulk formulation (\np{ln\_blk}\forcode{ = .true.} with four possible bulk algorithms),
+\item
+  a flux formulation (\np{ln\_flx}\forcode{ = .true.}),
+\item
+  a coupled or mixed forced/coupled formulation (exchanges with a atmospheric model via the OASIS coupler),
+(\np{ln\_cpl} or \np{ln\_mixcpl}\forcode{ = .true.}),
+\item
+  a user defined formulation (\np{ln\_usr}\forcode{ = .true.}).
 \end{itemize}
 
-Four different ways to provide the first six fields to the ocean are available which are controlled by
-namelist \ngn{namsbc} variables:
-an analytical formulation (\np{ln\_ana}\forcode{ = .true.}),
-a flux formulation (\np{ln\_flx}\forcode{ = .true.}),
-a bulk formulae formulation (CORE (\np{ln\_blk\_core}\forcode{ = .true.}),
-CLIO (\np{ln\_blk\_clio}\forcode{ = .true.}) bulk formulae) and
-a coupled or mixed forced/coupled formulation (exchanges with a atmospheric model via the OASIS coupler)
-(\np{ln\_cpl} or \np{ln\_mixcpl}\forcode{ = .true.}). 
-When used (\ie \np{ln\_apr\_dyn}\forcode{ = .true.}),
-the atmospheric pressure forces both ocean and ice dynamics.
 
 The frequency at which the forcing fields have to be updated is given by the \np{nn\_fsbc} namelist parameter.
-When the fields are supplied from data files (flux and bulk formulations),
-the input fields need not be supplied on the model grid.
-Instead a file of coordinates and weights can be supplied which maps the data from the supplied grid to
+
+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),
-can be masked to avoid spurious results in proximity of the coasts as
+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 
+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 addition of a surface restoring term to observed SST and/or SSS (\np{ln\_ssr}\forcode{ = .true.});
-\item
-  the modification of fluxes below ice-covered areas (using observed ice-cover or a sea-ice model)
-  (\np{nn\_ice}\forcode{ = 0..3});
-\item
-  the addition of river runoffs as surface freshwater fluxes or lateral inflow (\np{ln\_rnf}\forcode{ = .true.});
-\item
-  the addition of isf melting as lateral inflow (parameterisation) or
-  as fluxes applied at the land-ice ocean interface (\np{ln\_isf}) ; 
+  the local grid directions in the model,
+\item
+  the use of a land/sea mask for input fields (\np{nn\_lsm}\forcode{ = .true.}),
+\item
+  the addition of a surface restoring term to observed SST and/or SSS (\np{ln\_ssr}\forcode{ = .true.}),
+\item
+  the modification of fluxes below ice-covered areas (using climatological ice-cover or a sea-ice model)
+  (\np{nn\_ice}\forcode{ = 0..3}),
+\item
+  the addition of river runoffs as surface freshwater fluxes or lateral inflow (\np{ln\_rnf}\forcode{ = .true.}),
+\item
+  the addition of ice-shelf melting as lateral inflow (parameterisation) or
+  as fluxes applied at the land-ice ocean interface (\np{ln\_isf}\forcode{ = .true.}),
 \item
   the addition of a freshwater flux adjustment in order to avoid a mean sea-level drift
-  (\np{nn\_fwb}\forcode{ = 0..2});
-\item
-  the transformation of the solar radiation (if provided as daily mean) into a diurnal cycle
-  (\np{ln\_dm2dc}\forcode{ = .true.});
-\item
-  a neutral drag coefficient can be read from an external wave model (\np{ln\_cdgw}\forcode{ = .true.});
-\item
-  the Stokes drift rom an external wave model can be accounted (\np{ln\_sdw}\forcode{ = .true.}); 
-\item
-  the Stokes-Coriolis term can be included (\np{ln\_stcor}\forcode{ = .true.});
-\item
-  the surface stress felt by the ocean can be modified by surface waves (\np{ln\_tauwoc}\forcode{ = .true.}).
+  (\np{nn\_fwb}\forcode{ = 0..2}),
+\item
+  the transformation of the solar radiation (if provided as daily mean) into an analytical diurnal cycle
+  (\np{ln\_dm2dc}\forcode{ = .true.}),
+\item
+  the activation of wave effects from an external wave model  (\np{ln\_wave}\forcode{ = .true.}),
+\item
+  a neutral drag coefficient is read from an external wave model (\np{ln\_cdgw}\forcode{ = .true.}),
+\item
+  the Stokes drift from an external wave model is accounted for (\np{ln\_sdw}\forcode{ = .true.}), 
+\item
+  the choice of the Stokes drift profile parameterization (\np{nn\_sdrift}\forcode{ = 0..2}), 
+\item
+  the surface stress given to the ocean is modified by surface waves (\np{ln\_tauwoc}\forcode{ = .true.}),
+\item
+  the surface stress given to the ocean is read from an external wave model (\np{ln\_tauw}\forcode{ = .true.}),
+\item
+  the Stokes-Coriolis term is included (\np{ln\_stcor}\forcode{ = .true.}),
+\item
+  the light penetration in the ocean (\np{ln\_traqsr}\forcode{ = .true.} with namelist \ngn{namtra\_qsr}),
+\item
+  the atmospheric surface pressure gradient effect on ocean and ice dynamics (\np{ln\_apr\_dyn}\forcode{ = .true.} with namelist \ngn{namsbc\_apr}),
+\item
+  the effect of sea-ice pressure on the ocean (\np{ln\_ice\_embd}\forcode{ = .true.}).
 \end{itemize}
 
-In this chapter, we first discuss where the surface boundary condition appears in the model equations.
-Then we present the five ways of providing the surface boundary condition, 
+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.
+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:ICB_icebergs}),
@@ -95,9 +116,10 @@
 
 
+
 % ================================================================
 % Surface boundary condition for the ocean
 % ================================================================
 \section{Surface boundary condition for the ocean}
-\label{sec:SBC_general}
+\label{sec:SBC_ocean}
 
 The surface ocean stress is the stress exerted by the wind and the sea-ice on the ocean.
@@ -111,10 +133,10 @@
 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 with the atmosphere and sea-ice).
+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}). 
+(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 trends of the temperature equation (\mdl{traqsr} module) when
+It is applied as a 3D trend of the temperature equation (\mdl{traqsr} module) when
 \np{ln\_traqsr}\forcode{ = .true.}.
 The way the light penetrates inside the water column is generally a sum of decreasing exponentials
@@ -124,9 +146,9 @@
 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 both the ocean in two different ways:
-$(i)$  it changes the volume of the ocean and therefore appears in the sea surface height equation as
+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 the atmosphere, the sea-ice and the ice shelves. 
+the mass exchanged with atmosphere, sea-ice and ice shelves.
 
 
@@ -157,5 +179,5 @@
 the surface currents, temperature and salinity.  
 These variables are averaged over \np{nn\_fsbc} time-step (\autoref{tab:ssm}), and
-it is these averaged fields which are used to computes the surface fluxes at a frequency of \np{nn\_fsbc} time-step.
+these averaged fields are used to compute the surface fluxes at the frequency of \np{nn\_fsbc} time-steps.
 
 
@@ -165,14 +187,14 @@
     \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
+      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{
       \protect\label{tab:ssm}
       Ocean variables provided by the ocean to the surface module (SBC).
-      The variable are averaged over nn{\_}fsbc time step,
+      The variable are averaged over \np{nn\_fsbc} time-step,
       \ie the frequency of computation of surface fluxes.
     }
@@ -184,4 +206,5 @@
 
 
+
 % ================================================================
 %       Input Data 
@@ -191,10 +214,10 @@
 
 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 specify in \NEMO.
-This task is archieved by \mdl{fldread}.
-The module was design with four main objectives in mind: 
+(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 at model time-step, whatever their input frequency is,
+  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
@@ -204,11 +227,11 @@
 \item
   provide a simple user interface and a rather simple developer interface by
-  limiting the number of prerequisite information. 
-\end{enumerate}  
-
-As a results the user have only to fill in for each variable a structure in the namelist file to
+  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 on-the-fly interpolation.
+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,
@@ -220,6 +243,7 @@
 
 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 use can set the \np{cn\_dir} to the pathway leading to the data.
-By default, the data are assumed to have been copied so that cn\_dir='./'.
+the code is executed, then the user can set the \np{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='./'.
+
 
 % -------------------------------------------------------------------------------------------------------------
@@ -238,5 +262,5 @@
 \begin{description}  
 \item[File name]:
-  the stem name of the NetCDF file to be open.
+  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).
@@ -249,12 +273,12 @@
       \begin{tabular}{|l|c|c|c|}
         \hline
-        & daily or weekLLL	        & monthly                   &   yearly          \\   \hline
-        \np{clim}\forcode{ = .false.}	& fn\_yYYYYmMMdDD.nc  &   fn\_yYYYYmMM.nc   &   fn\_yYYYY.nc  \\   \hline
-        \np{clim}\forcode{ = .true.}	 	   & not possible 	              &  fn\_m??.nc             &   fn                \\   \hline
+                                        &  daily or weekLL     &  monthly           &  yearly        \\   \hline
+        \np{clim}\forcode{ = .false.}	&  fn\_yYYYYmMMdDD.nc  &  fn\_yYYYYmMM.nc   &  fn\_yYYYY.nc  \\   \hline
+        \np{clim}\forcode{ = .true.}	&  not possible        &  fn\_m??.nc        &  fn            \\   \hline
       \end{tabular}
     \end{center}
     \caption{
       \protect\label{tab:fldread}
-      naming nomenclature for climatological or interannual input file, as a function of the Open/close frequency.
+      naming nomenclature for climatological or interannual input file(s), 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
@@ -263,5 +287,5 @@
       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.
+      (2) when using AGRIF, the prefix '\_N' is added to files, where 'N' is the child grid number.
     }
   \end{table}
@@ -273,6 +297,6 @@
   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, seting it to '24.' can be interpreted as 240!
+  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]:
@@ -285,5 +309,5 @@
   00h00'00'' to 23h59'59".
   If set to 'true', the forcing will have a broken line shape.
-  Records are assumed to be dated the middle of the forcing period.
+  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. 
@@ -292,6 +316,6 @@
   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 exceed the one of the file.
-  See the above the file naming strategy which impacts the expected name of the file to be opened. 
+  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]:
@@ -302,5 +326,5 @@
   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. 
+  the experiment is not starting at the beginning of the year.
 
 \item[Others]:
@@ -315,10 +339,10 @@
 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,
+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} time-step.
 For example with \np{nn\_fsbc}\forcode{ = 3}, the surface module will be called at time-steps 1, 4, 7, etc.
-The date used for the time interpolation is thus redefined to be at the middle of \np{nn\_fsbc} time-step period.
+The date used for the time interpolation is thus redefined to the middle of \np{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.
@@ -326,5 +350,5 @@
 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
-be start Jan 1st at 12h00'00" and end Dec 31st at 12h00'00". \\
+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.
@@ -334,7 +358,7 @@
 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.
+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.
+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,
@@ -354,11 +378,11 @@
 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, a file of weights to be used to
+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 can be used to generate the weights, but the variables in
+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 interpolation.
+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
@@ -366,9 +390,13 @@
 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' it must have the same horizontal and vertical dimensions of
-the associated variable and should be equal to 1 over land and 0 elsewhere.
-The procedure can be recursively applied setting nn\_lsm > 1 in namsbc namelist.
-Note that nn\_lsm=0 forces the code to not apply the procedure even if a file for land/sea mask is supplied.
-
+The 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.
+
+
+% -------------------------------------------------------------------------------------------------------------
+% Bilinear interpolation
+% -------------------------------------------------------------------------------------------------------------
 \subsubsection{Bilinear interpolation}
 \label{subsec:SBC_iof_bilinear}
@@ -376,5 +404,5 @@
 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 to be applied.
+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.
@@ -392,9 +420,13 @@
 and wgt(1) corresponds to variable "wgt01" for example.
 
+
+% -------------------------------------------------------------------------------------------------------------
+% Bicubic interpolation
+% -------------------------------------------------------------------------------------------------------------
 \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.
+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:
 
@@ -402,12 +434,16 @@
   \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))} }
+    +  \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 absorbed into the weights.
-
+the spatial dependency has been included into the weights.
+
+
+% -------------------------------------------------------------------------------------------------------------
+% Implementation
+% -------------------------------------------------------------------------------------------------------------
 \subsubsection{Implementation}
 \label{subsec:SBC_iof_imp}
@@ -421,12 +457,12 @@
 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 not to be cyclic.
+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
+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.)
+(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,
@@ -445,4 +481,8 @@
 or is a copy of one from the first few columns on the opposite side of the grid (cyclical case).
 
+
+% -------------------------------------------------------------------------------------------------------------
+% Limitations
+% -------------------------------------------------------------------------------------------------------------
 \subsubsection{Limitations}
 \label{subsec:SBC_iof_lim}
@@ -450,5 +490,5 @@
 \begin{enumerate}  
 \item
-  The case where input data grids are not logically rectangular has not been tested.
+  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
@@ -471,16 +511,17 @@
 (see the directory NEMOGCM/TOOLS/WEIGHTS).
 
+
 % -------------------------------------------------------------------------------------------------------------
 % Standalone Surface Boundary Condition Scheme
 % -------------------------------------------------------------------------------------------------------------
-\subsection{Standalone surface boundary condition scheme}
-\label{subsec:SAS_iof}
-
-%---------------------------------------namsbc_ana--------------------------------------------------
+\subsection{Standalone surface boundary condition scheme (SAS)}
+\label{subsec:SAS}
+
+%---------------------------------------namsbc_sas--------------------------------------------------
 
 \nlst{namsbc_sas}
 %--------------------------------------------------------------------------------------------------------------
 
-In some circumstances it may be useful to avoid calculating the 3D temperature,
+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:
@@ -497,11 +538,11 @@
   Spinup of the iceberg floats
 \item
-  Ocean/sea-ice simulation with both media running in parallel (\np{ln\_mixcpl}\forcode{ = .true.})
+  Ocean/sea-ice simulation with both models running in parallel (\np{ln\_mixcpl}\forcode{ = .true.})
 \end{itemize}
 
-The StandAlone Surface scheme provides this utility.
+The Standalone Surface scheme provides this capacity.
 Its options are defined through the \ngn{namsbc\_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).
+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:
@@ -525,5 +566,5 @@
   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 make sure that nn{\_}date0 in the model namelist is correct for his or her purposes.
+  so the user must check that nn{\_}date0 in the model namelist is correct for his or her purposes.
 \item
   \mdl{stpctl}:
@@ -544,5 +585,5 @@
   velocity arrays at the surface.
   These filenames are supplied in namelist namsbc{\_}sas.
-  Unfortunately because of limitations with the \mdl{iom} module,
+  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.
@@ -551,34 +592,7 @@
 
 
-% Missing the description of the 2 following variables:
-%   ln_3d_uve   = .true.    !  specify whether we are supplying a 3D u,v and e3 field
-%   ln_read_frq = .false.    !  specify whether we must read frq or not
-
-
-
-% ================================================================
-% Analytical formulation (sbcana module) 
-% ================================================================
-\section[Analytical formulation (\textit{sbcana.F90})]
-{Analytical formulation (\protect\mdl{sbcana})}
-\label{sec:SBC_ana}
-
-%---------------------------------------namsbc_ana--------------------------------------------------
-%
-%\nlst{namsbc_ana}
-%--------------------------------------------------------------------------------------------------------------
-
-The analytical formulation of the surface boundary condition is the default scheme.
-In this case, all the six fluxes needed by the ocean are assumed to be uniform in space.
-They take constant values given in the namelist \ngn{namsbc{\_}ana} by
-the variables \np{rn\_utau0}, \np{rn\_vtau0}, \np{rn\_qns0}, \np{rn\_qsr0}, and \np{rn\_emp0}
-($\textit{emp}=\textit{emp}_S$).
-The runoff is set to zero.
-In addition, the wind is allowed to reach its nominal value within a given number of time steps (\np{nn\_tau000}).
-
-If a user wants to apply a different analytical forcing,
-the \mdl{sbcana} module can be modified to use another scheme.
-As an example, the \mdl{sbc\_ana\_gyre} routine provides the analytical forcing for the GYRE configuration
-(see GYRE configuration manual, in preparation).
+The user can also choose in the \ngn{namsbc\_sas} namelist to read the mean (nn\_fsbc time-step) fraction of solar net radiation absorbed in the 1st T level using
+ (\np{ln\_flx}\forcode{ = .true.}) and to provide 3D oceanic velocities instead of 2D ones (\np{ln\_flx}\forcode{ = .true.}). In that last case, only the 1st level will be read in.
+
 
 
@@ -605,63 +619,49 @@
 
 
+
 % ================================================================
 % Bulk formulation
 % ================================================================
-\section[Bulk formulation {(\textit{sbcblk\{\_core,\_clio\}.F90})}]
-{Bulk formulation {(\protect\mdl{sbcblk\_core}, \protect\mdl{sbcblk\_clio})}}
+\section[Bulk formulation (\textit{sbcblk.F90})]
+{Bulk formulation (\protect\mdl{sbcblk})}
 \label{sec:SBC_blk}
-
-In the bulk formulation, the surface boundary condition fields are computed using bulk formulae and atmospheric fields and ocean (and ice) variables.
+%---------------------------------------namsbc_blk--------------------------------------------------
+
+\nlst{namsbc_blk}
+%--------------------------------------------------------------------------------------------------------------
+
+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} time-step.
 
 The atmospheric fields used depend on the bulk formulae used.
-Two bulk formulations are available:
-the CORE and the CLIO bulk formulea.
+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\_core} or \np{ln\_clio}.
-
-Note:
-in forced mode, when a sea-ice model is used, a bulk formulation (CLIO or CORE) have to be used.
-Therefore the two bulk (CLIO and CORE) formulea include the computation of the fluxes over
-both an ocean and an ice surface. 
-
-% -------------------------------------------------------------------------------------------------------------
-%        CORE Bulk formulea
-% -------------------------------------------------------------------------------------------------------------
-\subsection[CORE formulea (\textit{sbcblk\_core.F90}, \forcode{ln_core = .true.})]
-{CORE formulea (\protect\mdl{sbcblk\_core}, \protect\np{ln\_core}\forcode{ = .true.})}
-\label{subsec:SBC_blk_core}
-%------------------------------------------namsbc_core----------------------------------------------------
-%
-%\nlst{namsbc_core}
-%-------------------------------------------------------------------------------------------------------------
-
-The CORE bulk formulae have been developed by \citet{large.yeager_rpt04}.
-They have been designed to handle the CORE 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 10 metre 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/CORE.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}.
-
-Options are defined through the  \ngn{namsbc\_core} namelist variables.
-The required 8 input fields are:
+ \np{ln\_NCAR}, \np{ln\_COARE\_3p0},  \np{ln\_COARE\_3p5} and  \np{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}), and \citet{lupkes.gryanik_JGR15} (\np{ln\_Cd\_L15}) parameterizations
+
+Common options are defined through the \ngn{namsbc\_blk} namelist variables.
+The required 9 input fields are:
 
 %--------------------------------------------------TABLE--------------------------------------------------
 \begin{table}[htbp]
-  \label{tab:CORE}
+  \label{tab:BULK}
   \begin{center}
     \begin{tabular}{|l|c|c|c|}
       \hline
-      Variable desciption					& 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
+      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}
   \end{center}
@@ -682,52 +682,81 @@
 \np{rn\_zu}: is the height of wind measurements (m)
 
-Three multiplicative factors are availables: 
-\np{rn\_pfac} and \np{rn\_efac} allows to adjust (if necessary) the global freshwater budget by
+Three multiplicative factors are available: 
+\np{rn\_pfac} and \np{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}, control to which extend the ice/ocean velocities are taken into account in
 the calculation of surface wind stress.
-Its range should be between zero and one, and it is recommended to set it to 0.
-
-% -------------------------------------------------------------------------------------------------------------
-%        CLIO Bulk formulea
-% -------------------------------------------------------------------------------------------------------------
-\subsection[CLIO formulea (\textit{sbcblk\_clio.F90}, \forcode{ln_clio = .true.})]
-{CLIO formulea (\protect\mdl{sbcblk\_clio}, \protect\np{ln\_clio}\forcode{ = .true.})}
-\label{subsec:SBC_blk_clio}
-%------------------------------------------namsbc_clio----------------------------------------------------
-%
-%\nlst{namsbc_clio}
-%-------------------------------------------------------------------------------------------------------------
-
-The CLIO bulk formulae were developed several years ago for the Louvain-la-neuve coupled ice-ocean model
-(CLIO, \cite{goosse.deleersnijder.ea_JGR99}). 
-They are simpler bulk formulae.
-They assume the stress to be known and compute the radiative fluxes from a climatological cloud cover. 
-
-Options are defined through the  \ngn{namsbc\_clio} namelist variables.
-The required 7 input fields are:
-
-%--------------------------------------------------TABLE--------------------------------------------------
-\begin{table}[htbp]
-  \label{tab:CLIO}
-  \begin{center}
-    \begin{tabular}{|l|l|l|l|}
-      \hline
-      Variable desciption				& Model variable	& Units				& point \\	\hline
-      i-component of the ocean stress		& utau			& $N.m^{-2}$			& U \\	\hline
-      j-component of the ocean stress		& vtau			& $N.m^{-2}$			& V \\	\hline
-      Wind speed module					& vatm			& $m.s^{-1}$			& T \\	\hline
-      10m air temperature					& tair			& \r{}$K$				& T \\	\hline
-      Specific humidity						& humi			& \%					& T \\	\hline
-      Cloud cover							& 				& \%					& T \\	\hline
-      Total precipitation (liquid + solid)	& precip		& $Kg.m^{-2}.s^{-1}$	& T \\	\hline
-      Solid precipitation 					& snow			& $Kg.m^{-2}.s^{-1}$	& T \\	\hline
-    \end{tabular}
-  \end{center}
-\end{table}
-%--------------------------------------------------------------------------------------------------------------
+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\_core or namsbc\_blk\_clio namelist (see \autoref{subsec:SBC_fldread}). 
+the namsbc\_blk namelist (see \autoref{subsec:SBC_fldread}). 
+
+
+% -------------------------------------------------------------------------------------------------------------
+%        Ocean-Atmosphere Bulk formulae
+% -------------------------------------------------------------------------------------------------------------
+\subsection{Ocean-Atmosphere Bulk formulae}
+%\subsection[Ocean-Atmosphere Bulk formulae (\textit{sbcblk_algo\{\_ncar,\_coare,\_coare3p5,\_ecmwf}.F90})]
+\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{ln\_NCAR}\forcode{ = .true.}):
+  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{ln\_COARE\_3p0}\forcode{ = .true.}): 
+  See \citet{fairall.bradley.ea_JC03} for more details
+\item
+  COARE 3.5 (\np{ln\_COARE\_3p5}\forcode{ = .true.}): 
+  See \citet{edson.jampana.ea_JPO13} for more details
+\item
+  ECMWF (\np{ln\_ECMWF}\forcode{ = .true.}): 
+  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}
+
+
+% -------------------------------------------------------------------------------------------------------------
+%        Ice-Atmosphere Bulk formulae
+% -------------------------------------------------------------------------------------------------------------
+\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{constant\ value}\forcode{ Cd_ice = 1.4e-3 }):
+  default constant value used for momentum and heat neutral transfer coefficients
+\item
+  \citet{lupkes.gryanik.ea_JGR12} (\np{ln\_Cd\_L12}\forcode{ = .true.}):
+  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{ln\_Cd\_L15}\forcode{ = .true.}):
+  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}
+
+
 
 % ================================================================
@@ -743,19 +772,17 @@
 
 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,
+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 (\key{oasis3}).
+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).
 
-Note that in addition to the setting of \np{ln\_cpl} to true, the \key{coupled} have to be defined.
-The CPP key is mainly used in sea-ice to ensure that the atmospheric fluxes are actually received by
-the ice-ocean system (no calculation of ice sublimation in coupled mode).
-When PISCES biogeochemical model (\key{top} and \key{pisces}) is also used in the coupled system, 
-the whole carbon cycle is computed by defining \key{cpl\_carbon\_cycle}.
+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 \ngn{namsbc{\_}cpl} ).
@@ -763,12 +790,11 @@
 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 namsbc{\_}cpl the number of categories will be determined by
+When indicating a multi-category coupling field in \ngn{namsbc{\_}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
+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.
-The new code has been tested using ECHAM with LIM2, and HadGAM3 with CICE but
-although it will compile with \key{lim3} additional minor code changes may be required to run using LIM3.
+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.
+
 
 
@@ -785,6 +811,6 @@
 
 The optional atmospheric pressure can be used to force ocean and ice dynamics
-(\np{ln\_apr\_dyn}\forcode{ = .true.}, \textit{\ngn{namsbc}} namelist).
-The input atmospheric forcing defined via \np{sn\_apr} structure (\textit{namsbc\_apr} namelist)
+(\np{ln\_apr\_dyn}\forcode{ = .true.}, \ngn{namsbc} namelist).
+The input atmospheric forcing defined via \np{sn\_apr} structure (\ngn{namsbc\_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
@@ -796,11 +822,11 @@
 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} 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 step.
+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 set in the output.
+$\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.
@@ -809,4 +835,6 @@
 the equivalent inverse barometer sea surface height $\eta_{ib}$ can be added to BDY ssh data: 
 \np{ln\_apr\_obc}  might be set to true.
+
+
 
 % ================================================================
@@ -835,5 +863,5 @@
 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 \rou{SBC/tide.h90} (this comprises the tidal
+defined in file \textit{SBC/tide.h90} (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
@@ -850,5 +878,5 @@
 discussion about the practical implementation of this term).
 Nevertheless, the complex calculations involved would make this
-computationally too expensive.  Here, two options are available:
+computationally too expensive. Here, two options are available:
 $\Pi_{sal}$ generated by an external model can be read in
 (\np{ln\_read\_load=.true.}), or a ``scalar approximation'' can be
@@ -861,4 +889,6 @@
 errors. Setting both \np{ln\_read\_load} and \np{ln\_scal\_load} to
 \forcode{.false.} removes the SAL contribution.
+
+
 
 % ================================================================
@@ -944,5 +974,5 @@
 As such the volume of water does not change, but the water is diluted.
 
-For the non-linear free surface case (\key{vvl}), no flux is allowed through the surface.
+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.
@@ -987,5 +1017,6 @@
 %To do this we need to treat evaporation/precipitation fluxes and river runoff differently in the 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/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:
 
-%}
+
+
 % ================================================================
 %        Ice shelf melting
@@ -998,4 +1029,5 @@
 \nlst{namsbc_isf}
 %--------------------------------------------------------------------------------------------------------
+
 The namelist variable in \ngn{namsbc}, \np{nn\_isf}, controls the ice shelf representation.
 Description and result of sensitivity test to \np{nn\_isf} are presented in \citet{mathiot.jenkins.ea_GMD17}. 
@@ -1003,7 +1035,9 @@
 
 \begin{description}
-\item[\np{nn\_isf}\forcode{ = 1}]:
+
+  \item[\np{nn\_isf}\forcode{ = 1}]:
   The ice shelf cavity is represented (\np{ln\_isfcav}\forcode{ = .true.} needed).
   The fwf and heat flux are depending of the local water properties.
+  
   Two different bulk formulae are available:
 
@@ -1060,5 +1094,5 @@
      This formulation has not been extensively tested in NEMO (not recommended).
    \end{description}
- \item[\np{nn\_isf}\forcode{ = 2}]:
+  \item[\np{nn\_isf}\forcode{ = 2}]:
    The ice shelf cavity is not represented.
    The fwf and heat flux are computed using the \citet{beckmann.goosse_OM03} parameterisation of isf melting.
@@ -1067,5 +1101,5 @@
    (\np{sn\_depmin\_isf}) as in (\np{nn\_isf}\forcode{ = 3}).
    The effective melting length (\np{sn\_Leff\_isf}) is read from a file.
- \item[\np{nn\_isf}\forcode{ = 3}]:
+  \item[\np{nn\_isf}\forcode{ = 3}]:
    The ice shelf cavity is not represented.
    The fwf (\np{sn\_rnfisf}) is prescribed and distributed along the ice shelf edge between
@@ -1073,5 +1107,5 @@
    the base of the ice shelf along the calving front (\np{sn\_depmin\_isf}).
    The heat flux ($Q_h$) is computed as $Q_h = fwf \times L_f$.
- \item[\np{nn\_isf}\forcode{ = 4}]:
+  \item[\np{nn\_isf}\forcode{ = 4}]:
    The ice shelf cavity is opened (\np{ln\_isfcav}\forcode{ = .true.} needed).
    However, the fwf is not computed but specified from file \np{sn\_fwfisf}).
@@ -1108,4 +1142,9 @@
 %>>>>>>>>>>>>>>>>>>>>>>>>>>>>
 
+
+
+% ================================================================
+%        Ice sheet coupling
+% ================================================================
 \section{Ice sheet coupling}
 \label{sec:SBC_iscpl}
@@ -1114,6 +1153,8 @@
 \nlst{namsbc_iscpl}
 %--------------------------------------------------------------------------------------------------------
+
 Ice sheet/ocean coupling is done through file exchange at the restart step.
 At each restart step:
+
 \begin{description}
 \item[Step 1]: the ice sheet model send a new bathymetry and ice shelf draft netcdf file.
@@ -1127,4 +1168,5 @@
 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]:
@@ -1165,5 +1207,6 @@
 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).
 
-%
+
+
 % ================================================================
 %        Handling of icebergs
@@ -1196,5 +1239,5 @@
   the geographical box: lonmin,lonmax,latmin,latmax
 \item[\np{nn\_test\_icebergs}\forcode{ = -1}]
-  In this scheme the model reads a calving file supplied in the \np{sn\_icb} parameter.
+  In this scheme, the model reads a calving file supplied in the \np{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.
@@ -1234,7 +1277,9 @@
 since its trajectory data may be spread across multiple files.
 
-% -------------------------------------------------------------------------------------------------------------
+
+
+% =============================================================================================================
 %        Interactions with waves (sbcwave.F90, ln_wave)
-% -------------------------------------------------------------------------------------------------------------
+% =============================================================================================================
 \section[Interactions with waves (\textit{sbcwave.F90}, \texttt{ln\_wave})]
 {Interactions with waves (\protect\mdl{sbcwave}, \protect\np{ln\_wave})}
@@ -1252,6 +1297,6 @@
 
 Physical processes related to ocean surface waves can be accounted by setting the logical variable 
-\np{ln\_wave}\forcode{= .true.} in \ngn{namsbc} namelist. In addition, specific flags accounting for 
-different porcesses should be activated as explained in the following sections.
+\np{ln\_wave} \forcode{= .true.} in \ngn{namsbc} 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:
@@ -1265,8 +1310,8 @@
 
 
-% ================================================================
+% ----------------------------------------------------------------
 % Neutral drag coefficient from wave model (ln_cdgw)
 
-% ================================================================
+% ----------------------------------------------------------------
 \subsection[Neutral drag coefficient from wave model (\texttt{ln\_cdgw})]
 {Neutral drag coefficient from wave model (\protect\np{ln\_cdgw})}
@@ -1275,12 +1320,12 @@
 The neutral surface drag coefficient provided from an external data source (\ie a wave model), 
 can be used by setting the logical variable \np{ln\_cdgw} \forcode{= .true.} in \ngn{namsbc} namelist. 
-Then using the routine \rou{turb\_ncar} and starting from the neutral drag coefficent provided, 
+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}. 
 
 
-% ================================================================
+% ----------------------------------------------------------------
 % 3D Stokes Drift (ln_sdw, nn_sdrift)
-% ================================================================
+% ----------------------------------------------------------------
 \subsection[3D Stokes Drift (\texttt{ln\_sdw}, \texttt{nn\_sdrift})]
 {3D Stokes Drift (\protect\np{ln\_sdw, nn\_sdrift})}
@@ -1292,7 +1337,7 @@
 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. 
+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.
+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: 
 
@@ -1309,5 +1354,5 @@
 $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 
+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.
@@ -1339,5 +1384,5 @@
 
 \item[\np{nn\_sdrift} = 1]: velocity profile based on the Phillips spectrum which is considered to be a 
-reasonable estimate of the part of the spectrum most contributing to the Stokes drift velocity near the surface
+reasonable estimate of the part of the spectrum mostly contributing to the Stokes drift velocity near the surface
 \citep{breivik.bidlot.ea_OM16}:
 
@@ -1377,7 +1422,7 @@
 
 
-% ================================================================
+% ----------------------------------------------------------------
 % Stokes-Coriolis term (ln_stcor)
-% ================================================================
+% ----------------------------------------------------------------
 \subsection[Stokes-Coriolis term (\texttt{ln\_stcor})]
 {Stokes-Coriolis term (\protect\np{ln\_stcor})}
@@ -1392,8 +1437,8 @@
 
 
-% ================================================================
+% ----------------------------------------------------------------
 % Waves modified stress (ln_tauwoc, ln_tauw)
-% ================================================================
-\subsection[Wave modified sress (\texttt{ln\_tauwoc}, \texttt{ln\_tauw})]
+% ----------------------------------------------------------------
+\subsection[Wave modified stress (\texttt{ln\_tauwoc}, \texttt{ln\_tauw})]
 {Wave modified sress (\protect\np{ln\_tauwoc, ln\_tauw})}
 \label{subsec:SBC_wave_tauw}
@@ -1402,7 +1447,7 @@
 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. 
+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: 
 
@@ -1434,4 +1479,5 @@
 
 
+
 % ================================================================
 % Miscellanea options
@@ -1439,4 +1485,5 @@
 \section{Miscellaneous options}
 \label{sec:SBC_misc}
+
 
 % -------------------------------------------------------------------------------------------------------------
@@ -1446,5 +1493,5 @@
 {Diurnal cycle (\protect\mdl{sbcdcy})}
 \label{subsec:SBC_dcy}
-%------------------------------------------namsbc_rnf----------------------------------------------------
+%------------------------------------------namsbc-------------------------------------------------------------
 %
 \nlst{namsbc} 
@@ -1468,7 +1515,6 @@
 
 \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.
-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}.
+%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,
@@ -1476,13 +1522,13 @@
 The \cite{bernie.guilyardi.ea_CD07} reconstruction algorithm is available in \NEMO by
 setting \np{ln\_dm2dc}\forcode{ = .true.} (a \textit{\ngn{namsbc}} namelist variable) when
-using CORE bulk formulea (\np{ln\_blk\_core}\forcode{ = .true.}) or
+using a bulk formulation (\np{ln\_blk}\forcode{ = .true.}) or
 the flux formulation (\np{ln\_flx}\forcode{ = .true.}).
 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 preserve the daily mean incoming SWF as the reconstructed SWF at
+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 and a time interpolation set to true in \np{sn\_qsr} namelist parameter).
-Furthermore, it is recommended to have a least 8 surface module time step per day,
+(\ie a frequency of 24 hours and a time interpolation set to true in \np{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,
@@ -1507,4 +1553,5 @@
 an inconsistency between the scale of the vertical resolution and the forcing acting on that scale.
 
+
 % -------------------------------------------------------------------------------------------------------------
 %        Rotation of vector pairs onto the model grid directions
@@ -1513,10 +1560,9 @@
 \label{subsec:SBC_rotation}
 
-When using a flux (\np{ln\_flx}\forcode{ = .true.}) or
-bulk (\np{ln\_clio}\forcode{ = .true.} or \np{ln\_core}\forcode{ = .true.}) formulation,
+When using a flux (\np{ln\_flx}\forcode{ = .true.}) or bulk (\np{ln\_blk}\forcode{ = .true.}) 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.
+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.
@@ -1527,4 +1573,5 @@
 The rot\_rep routine from the \mdl{geo2ocean} module is used to perform the rotation.
 
+
 % -------------------------------------------------------------------------------------------------------------
 %        Surface restoring to observed SST and/or SSS
@@ -1538,5 +1585,5 @@
 %-------------------------------------------------------------------------------------------------------------
 
-IOptions are defined through the \ngn{namsbc\_ssr} namelist variables.
+Options are defined through the \ngn{namsbc\_ssr} namelist variables.
 On forced mode using a flux formulation (\np{ln\_flx}\forcode{ = .true.}),
 a feedback term \emph{must} be added to the surface heat flux $Q_{ns}^o$:
@@ -1570,4 +1617,5 @@
 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.
+
 
 % -------------------------------------------------------------------------------------------------------------
@@ -1595,5 +1643,5 @@
   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 si IF case,
+  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.
@@ -1602,17 +1650,22 @@
   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 ocean fluxes.
-  Note that the activation of a sea-ice model is is done by defining a CPP key (\key{lim3} or \key{cice}).
+  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 LIM-3 or $3$ for CICE).
+  (\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
+
+
+% -------------------------------------------------------------------------------------------------------------
+%        CICE-ocean Interface
+% -------------------------------------------------------------------------------------------------------------
 \subsection[Interface to CICE (\textit{sbcice\_cice.F90})]
 {Interface to CICE (\protect\mdl{sbcice\_cice})}
 \label{subsec:SBC_cice}
 
-It is now possible to couple a regional or global NEMO configuration (without AGRIF)
+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
@@ -1621,5 +1674,5 @@
 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 CORE forcing option for NEMO
+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
@@ -1641,4 +1694,5 @@
 there is no sea ice.
 
+
 % -------------------------------------------------------------------------------------------------------------
 %        Freshwater budget control 
@@ -1648,7 +1702,8 @@
 \label{subsec:SBC_fwb}
 
-For global ocean simulation it can be useful to introduce a control of the mean sea level in order to
+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 the freshwater budget. 
+In \NEMO, two way of controlling the freshwater budget are proposed:
+ 
 \begin{description}
 \item[\np{nn\_fwb}\forcode{ = 0}]
@@ -1657,5 +1712,6 @@
 \item[\np{nn\_fwb}\forcode{ = 1}]
   global mean \textit{emp} set to zero at each model time step. 
-%Note that with a sea-ice model, this technique only control the mean sea level with linear free surface (\key{vvl} not defined) and no mass flux between ocean and ice (as it is implemented in the current ice-ocean coupling). 
+  %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{nn\_fwb}\forcode{ = 2}]
   freshwater budget is adjusted from the previous year annual mean budget which
@@ -1664,6 +1720,4 @@
   the change in the mean sea level at January the first and saved in the \textit{EMPav.dat} file. 
 \end{description}
-
-
 
 % Griffies doc:
@@ -1674,5 +1728,5 @@
 % 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, 
+% 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 
@@ -1689,4 +1743,5 @@
 % in ocean-ice models. 
 
+
 \biblio
 
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_STO.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_STO.tex	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_STO.tex	(revision 11353)
@@ -8,18 +8,25 @@
 \label{chap:STO}
 
-Authors: P.-A. Bouttier
+\minitoc
 
-\minitoc
+% \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}
+
+Authors: \\
+C. Levy release 4.0.1 update \\
+P.-A. Bouttier release 3.6 inital version
 
 \newpage
 
-The stochastic parametrization module aims to explicitly simulate uncertainties in the model.
-More particularly, \cite{brankart_OM13} has shown that,
-because 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 T/S large scale fields),
-and that the impact of these uncertainties can be simulated by
-random processes representing unresolved T/S fluctuations.
+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.
 
-The stochastic formulation of the equation of state can be written as:
+As detailed in \cite{brankart_OM13}, the stochastic formulation of the equation of state can be written as:
 \begin{equation}
   \label{eq:eos_sto}
@@ -27,5 +34,5 @@
 \end{equation}
 where $p_o(z)$ is the reference pressure depending on the depth and,
-$\Delta T_i$ and $\Delta S_i$ are a set of T/S perturbations defined as
+$\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}
@@ -33,5 +40,5 @@
   \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 processes (AR-1) with
+$\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.
@@ -41,12 +48,11 @@
 \label{sec:STO_the_details}
 
-The starting point of our implementation of stochastic parameterizations in NEMO is to observe that
-many existing parameterizations are based on autoregressive processes,
+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.
-A generic approach is thus to add one single new module in NEMO,
-generating processes with appropriate statistics to simulate each kind of uncertainty in the 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 every model grid point,
+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:
@@ -101,41 +107,39 @@
 \noindent
 In this way, higher order processes can be easily generated recursively using the same piece of code implementing
-(\autoref{eq:autoreg}), and using succesively processes from order $0$ to~$n-1$ as~$w^{(i)}$.
-The parameters in (\autoref{eq:ord2}) are computed so that this recursive application of
-(\autoref{eq:autoreg}) leads to processes with the required standard deviation and correlation timescale,
+\autoref{eq:autoreg}, and using successive processes from order $0$ to~$n-1$ as~$w^{(i)}$.
+The parameters in \autoref{eq:ord2} are computed so that this recursive application of
+\autoref{eq: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$ is increased.
+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 of lacking physics, a very important issues then to tune these new parameters using
+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}
 
-%---------------------------------------namsbc--------------------------------------------------
 
-\nlst{namsto}
-%--------------------------------------------------------------------------------------------------------------
+The code implementing stochastic parametrisation is located in the src/OCE/STO directory.
+It contains three modules : 
+% \begin{description}
 
-The computer code implementing stochastic parametrisations can be found in the STO directory.
-It involves three modules : 
-\begin{description}
-\item[\mdl{stopar}:]
-  define the Stochastic parameters and their time evolution.
-\item[\mdl{storng}:]
-  a random number generator based on (and includes) the 64-bit KISS (Keep It Simple Stupid) random number generator
-  distributed by George Marsaglia
-  (see \href{https://groups.google.com/forum/#!searchin/comp.lang.fortran/64-bit$20KISS$20RNGs}{here})
-\item[\mdl{stopts}:]
-  stochastic parametrisation associated with the non-linearity of the equation of seawater,
-  implementing \autoref{eq:sto_pert} and specific piece of code in
-  the equation of state implementing \autoref{eq:eos_sto}.
-\end{description}
+\mdl{stopar} : define the Stochastic parameters and their time evolution
 
-The \mdl{stopar} module has 3 public routines to be called by the model (in our case, NEMO):
+\mdl{storng} : random number generator based on and including the 64-bit KISS (Keep It Simple Stupid) random number generator distributed by George Marsaglia
 
-The first routine (\rou{sto\_par}) is a direct implementation of (\autoref{eq:autoreg}),
+\mdl{stopts} : stochastic parametrisation associated with the non-linearity of the equation of
+ seawater, implementing \autoref{eq:sto_pert} so as specifics in the equation of state
+ implementing \autoref{eq: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: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$).
@@ -143,14 +147,37 @@
 to introduce a spatial correlation between the stochastic processes.
 
-The second routine (\rou{sto\_par\_init}) is an initialization routine mainly dedicated to
-the computation of parameters $a^{(i)}, b^{(i)}, c^{(i)}$ for each autoregressive process,
+(\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.
 
-Parameters for the processes can be specified through the following \ngn{namsto} namelist parameters:
+(\rou{sto\_rst\_write}) writes a restart file
+(which suffix name is given by \np{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} is set to \forcode{.true.}),
+the restart file (which suffix name is given by \np{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} 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} 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 \ngn{namsto} namelist(only the subset for equation of state stochastic parametrisation is listed below):
+%---------------------------------------namsto--------------------------------------------------
+
+\nlst{namsto}
+%--------------------------------------------------------------------------------------------------------------
+
+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}:]   number of independent random walks
-\item[\np{rn\_eos\_stdxy}:] random walk horz. standard deviation (in grid points)
-\item[\np{rn\_eos\_stdz}:]  random walk vert. standard deviation (in grid points)
+\item[\np{rn\_eos\_stdxy}:] random walk horizontal standard deviation (in grid points)
+\item[\np{rn\_eos\_stdz}:]  random walk vertical standard deviation (in grid points)
 \item[\np{rn\_eos\_tcor}:]  random walk time correlation (in timesteps)
 \item[\np{nn\_eos\_ord}:]   order of autoregressive processes
@@ -158,17 +185,6 @@
 \item[\np{rn\_eos\_lim}:]   limitation factor (default = 3.0)
 \end{description}
-This routine also includes the initialization (seeding) of the random number generator.
 
-The third routine (\rou{sto\_rst\_write}) writes a restart file
-(which suffix name is given by \np{cn\_storst\_out} namelist parameter) containing the current value of
-all autoregressive processes to allow restarting a simulation from where it has been interrupted.
-This file also contains the current state of the random number generator.
-When \np{ln\_rststo} is set to \forcode{.true.}),
-the restart file (which suffix name is given by \np{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} is set to \forcode{.true.},
-\ie when the state of the random number generator is read in the restart file.
-
+The first four parameters define the stochastic part of equation of state.
 \biblio
 
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_ZDF.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_ZDF.tex	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_ZDF.tex	(revision 11353)
@@ -997,6 +997,6 @@
 %       Non-Linear Bottom Friction
 % -------------------------------------------------------------------------------------------------------------
- \subsection[Non-linear top/bottom friction (\forcode{ln_no_lin = .true.})]
- {Non-linear top/bottom friction (\protect\np{ln\_no\_lin}\forcode{ = .true.})}
+ \subsection[Non-linear top/bottom friction (\forcode{ln_non_lin = .true.})]
+ {Non-linear top/bottom friction (\protect\np{ln\_non\_lin}\forcode{ = .true.})}
  \label{subsec:ZDF_drg_nonlinear}
 
@@ -1235,5 +1235,30 @@
 \label{subsec:ZDF_swm}
 
-TBC ...
+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: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})
 
 % ================================================================
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_misc.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_misc.tex	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_misc.tex	(revision 11353)
@@ -30,13 +30,9 @@
 are much narrow than even a single ocean grid-point.
 
-We describe briefly here the three methods that can be used in \NEMO to handle such improperly resolved straits.
-The first two consist of opening the strait by hand while ensuring that the mass exchanges through
-the strait are not too large by either artificially reducing the surface of the strait grid-cells or,
-locally increasing the lateral friction.
-In the third one, the strait is closed but exchanges of mass, heat and salt across the land are allowed.
-Note that such modifications are so specific to a given configuration that no attempt has been made to
-set them in a generic way.
-However, examples of how they can be set up is given in the ORCA 2\deg and 0.5\deg configurations.
-For example, for details of implementation in ORCA2, search: \texttt{IF( cp\_cfg == "orca" .AND. jp\_cfg == 2 )}
+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.
 
 % -------------------------------------------------------------------------------------------------------------
@@ -46,17 +42,45 @@
 \label{subsec:MISC_strait_hand}
 
-$\bullet$ reduced 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 that would require a reduction of the model time step.
-The changes associated with strait management are done in \mdl{domhgr},
-just after the definition or reading of the horizontal scale factors. 
-
-$\bullet$ increase of the viscous boundary layer thickness by local increase of the fmask value at the coast
-(\autoref{fig:MISC_strait_hand}).
-This is done in \mdl{dommsk} together with the setting of the coastal value of fmask (see  \autoref{sec:LBC_coast}).
+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} 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} 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} 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.
 
 %>>>>>>>>>>>>>>>>>>>>>>>>>>>>
@@ -175,62 +199,60 @@
 \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.
-The existing 'zoom' options are overly complex for this task and marked for deletion anyway.
-This alternative subsetting operates for the j-direction only and works by optionally looking for and
-using a global file attribute (named: \np{open\_ocean\_jstart}) to determine the starting j-row for input.
-The use of this option is best explained with an example:
-consider an ORCA1 configuration using the extended grid bathymetry and coordinate files:
-\vspace{-10pt}
-\ifile{eORCA1\_bathymetry\_v2}
-\ifile{eORCA1\_coordinates}
-\noindent These files define a horizontal domain of 362x332.
-Assuming 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} 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 coordinates and bathymetry files 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:
-
-\noindent Add the new attribute to any input files requiring a j-row offset, i.e:
-\vspace{-10pt}
+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}) 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} 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} to \ngn{namcfg} in the configuration
+namelist (if it is not already there) and set \np{.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} + 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} is active. The \texttt{ncap2} tool provides a
+convenient way of achieving this:
+
 \begin{cmds}
-ncatted  -a open_ocean_jstart,global,a,d,41 eORCA1_coordinates.nc 
-ncatted  -a open_ocean_jstart,global,a,d,41 eORCA1_bathymetry_v2.nc
+ncap2 -s 'jpjglo=292' eORCA1_domcfg.nc nORCA1_domcfg.nc
 \end{cmds}
- 
-\noindent Add the logical switch to \ngn{namcfg} in the configuration namelist and set true:
-%--------------------------------------------namcfg--------------------------------------------------------
-
-\nlst{namcfg}
-%--------------------------------------------------------------------------------------------------------------
-
-\noindent Note the j-size of the global domain is the (extended j-size minus \np{open\_ocean\_jstart} + 1 ) and
-this must match the size of all datasets other than bathymetry and coordinates currently.
-However the option can be extended to any global, 2D and 3D, netcdf, input field by adding the:
-\vspace{-10pt}
+
+The domain configuration file is unique in this respect since it also contains the value
+of \texttt{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}.
 \begin{forlines}
 lrowattr=ln_use_jattr
 \end{forlines}
-optional argument to the appropriate \np{iom\_get} call and the \np{open\_ocean\_jstart} attribute to
-the corresponding input files.
-It remains the users responsibility to set \np{jpjdta} and \np{jpjglo} values in
-the \np{namelist\_cfg} file according to their needs.
-
-%>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-\begin{figure}[!ht]
-  \begin{center}
-    \includegraphics[width=\textwidth]{Fig_LBC_zoom}
-    \caption{
-      \protect\label{fig:LBC_zoom}
-      Position of a model domain compared to the data input domain when the zoom functionality is used.
-    }
-  \end{center}
-\end{figure}
-%>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-
+
+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.
 
 % ================================================================
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_model_basics.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_model_basics.tex	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/chap_model_basics.tex	(revision 11353)
@@ -32,6 +32,8 @@
 \begin{enumerate}
 \item
-  \textit{spherical earth approximation}: the geopotential surfaces are assumed to be spheres so that
-  gravity (local vertical) is parallel to the earth's radius
+  \textit{spherical Earth approximation}: the geopotential surfaces are assumed to be oblate spheriods
+  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
@@ -63,8 +65,14 @@
     \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-Vaisala 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{enumerate}
 
 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
+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.
@@ -107,6 +115,7 @@
 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.
-Both $H$ and $\eta$ are usually referenced to a given surface, $z = 0$, chosen as a mean sea surface
+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:ocean_bc}).
 Through these two boundaries, the ocean can exchange fluxes of heat, fresh water, salt, and momentum with
@@ -210,5 +219,5 @@
 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 would have to be very short if they were present in the model.
+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$.
@@ -217,5 +226,5 @@
 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 the this document (see the next sub-section).
+Only the free surface formulation is now described in this document (see the next sub-section).
 
 % -------------------------------------------------------------------------------------------------------------
@@ -237,5 +246,5 @@
 Allowing the air-sea interface to move introduces the external gravity waves (EGWs) as
 a class of solution of the primitive equations.
-These waves are barotropic because of hydrostatic assumption, and their phase speed is quite high.
+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.
 
@@ -266,5 +275,5 @@
 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
+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}
@@ -338,5 +347,5 @@
 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:PE_dyn} to \autoref{eq:PE_eos}) can be written in the tensorial form,
+(\autoref{eq:PE_dyn} to \autoref{eq:PE_eos}) can then be written in the tensorial form,
 invariant in any orthogonal horizontal curvilinear coordinate system transformation:
 \begin{subequations}
@@ -384,5 +393,5 @@
 \end{gather}
 
-Using the fact that the horizontal scale factors $e_1$ and $e_2$ are independent of $k$ and that
+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:PE_dyn} can be transformed as follows:
@@ -456,5 +465,5 @@
   &      &= &\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) \\
-  \intertext{as $\nabla \cdot {\vect U} \; = 0$ (incompressibility) it comes:}
+  \intertext{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*}
@@ -516,5 +525,5 @@
     % \label{eq:PE_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_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}
@@ -526,5 +535,5 @@
     p_s = \rho \,g \, \eta
   \]
-  with $\eta$ is solution of \autoref{eq:PE_ssh}.
+  and $\eta$ is the solution of \autoref{eq:PE_ssh}.
 
   The vertical velocity and the hydrostatic pressure are diagnosed from the following equations:
@@ -536,15 +545,16 @@
   \]
   where the divergence of the horizontal velocity, $\chi$ is given by \autoref{eq:PE_div_Uh}.
-\item \textit{tracer equations}:
-  \[
-    %\label{eq:S}
-    \pd[T]{t} = - \frac{1}{e_1 e_2} \lt[ \pd[(e_2 T \, u)]{i} + \pd[(e_1 T \, v)]{j} \rt]
+
+\item 
+  \textbf{tracer equations}:
+  \begin{equation}
+  \begin{split}
+    \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 \\
-    %\label{eq: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
-    %\label{eq:rho}
-    \rho = \rho \big( T,S,z(k) \big)
-  \]
+    \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{split}
+  \end{equation}
 \end{itemize}
 
@@ -575,5 +585,5 @@
 follows the isopycnal surfaces, \eg an isopycnic coordinate.
 
-In order to satisfy two or more constrains one can even be tempted to mixed these coordinate systems, as in
+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
@@ -594,5 +604,5 @@
 This so-called \textit{generalised vertical coordinate} \citep{kasahara_MWR74} is in fact
 an Arbitrary Lagrangian--Eulerian (ALE) coordinate.
-Indeed, choosing an expression for $s$ is an arbitrary choice that determines
+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).
@@ -601,13 +611,13 @@
 Its most often used implementation is via an ALE algorithm,
 in which a pure lagrangian step is followed by regridding and remapping steps,
-the later step implicitly embedding the vertical advection
+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
+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.
 
 %\gmcomment{
 %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,
+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.
@@ -615,5 +625,5 @@
 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 the vertical coordinate, be it geopotential,
+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
@@ -660,5 +670,5 @@
 \[
   % \label{eq:PE_sco_w}
-  \omega = w - e_3 \, \pd[s]{t} - \sigma_1 \, u - \sigma_2 \, v
+  \omega = w -  \, \lt. \pd[z]{t} \rt|_s - \sigma_1 \, u - \sigma_2 \, v
 \]
 
@@ -671,5 +681,5 @@
   % \label{eq:PE_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
+                - \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{multline*}
@@ -677,5 +687,5 @@
   % \label{eq:PE_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
+                - \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{multline*}
@@ -687,5 +697,5 @@
                                        - \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}
+                                       - g \frac{\rho}{\rho_o} \sigma_1 + D_u^{\vect U} + F_u^{\vect U}
   \end{multline*}
   \begin{multline*}
@@ -695,5 +705,5 @@
                                        - \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}
+                                       - g \frac{\rho}{\rho_o}\sigma_2 + D_v^{\vect U} + F_v^{\vect U}
   \end{multline*}
   where the relative vorticity, $\zeta$, the surface pressure gradient,
@@ -750,5 +760,5 @@
 %>>>>>>>>>>>>>>>>>>>>>>>>>>>>
 
-In that case, the free surface equation is nonlinear, and the variations of volume are fully taken into account.
+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.
 
@@ -766,8 +776,13 @@
 The position (\zstar) and vertical discretization (\zstar) are expressed as:
 \[
-  % \label{eq:z-star}
+  % \label{eq:PE_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}
+              = \frac{H + \eta}{H} .
+\]
+Simple re-organisation of the above expressions gives
+\[
+  % \label{eq:PE_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,
@@ -776,15 +791,7 @@
 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) (r \; w *) = 0
+  \pd[r]{t} = \nabla_{\zstar} \cdot \lt( r \; \vect U_h \rt) + \pd[r \; w^*]{\zstar} = 0 .
 \]
-
-% from MOM4p1 documentation
-To overcome problems with vanishing surface and/or bottom cells, we consider the zstar coordinate 
-\[
-  % \label{eq:PE_}
-  \zstar = H \lt( \frac{z - \eta}{H + \eta} \rt)
-\]
-
-This coordinate is closely related to the "eta" coordinate used in many atmospheric models
+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,
@@ -798,5 +805,5 @@
 These properties greatly reduce difficulties of computing the horizontal pressure gradient relative to
 terrain following sigma models discussed in \autoref{subsec:PE_sco}.
-Additionally, since \zstar when $\eta = 0$,
+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
@@ -804,21 +811,21 @@
 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
+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$.
+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 ver tical increments yields the time independent ocean depth. %k ds = H.
+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 proper ty means that no spurious vertical transport is induced across surfaces of constant \zstar by
+This property means that no spurious vertical transport is induced across surfaces of constant \zstar  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 \zstar coordinate is a very convenient property that
-allows for a nearly arbitrary ver tical resolution even in the presence of large amplitude fluctuations of
+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 %%%
@@ -870,9 +877,9 @@
 \begin{equation}
   \label{eq:PE_p_sco}
-  \nabla p |_z = \nabla p |_s - \pd[p]{s} \nabla z |_s
+  \nabla p |_z = \nabla p |_s - \frac{1}{e_3} \pd[p]{s} \nabla z |_s
 \end{equation}
 
 The second term in \autoref{eq:PE_p_sco} depends on the tilt of the coordinate surface and
-introduces a truncation error that is not present in a $z$-model.
+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.
@@ -887,5 +894,5 @@
 However, the definition of the model domain vertical coordinate becomes then a non-trivial thing for
 a realistic bottom topography:
-a envelope topography is defined in $s$-coordinate on which a full or
+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{sec:DOM_zgr}.
@@ -922,5 +929,5 @@
 
 The \ztilde -coordinate has been developed by \citet{leclair.madec_OM11}.
-It is available in \NEMO since the version 3.4.
+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.
@@ -934,5 +941,5 @@
 \label{sec:PE_zdf_ldf}
 
-The primitive equations describe the behaviour of a geophysical fluid at space and time scales larger than
+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.
@@ -984,5 +991,5 @@
 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-Vais\"{a}l\"{a} frequency...),
+(\eg Richardson number, Brunt-Vais\"{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}).
@@ -1016,5 +1023,5 @@
 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} have proposed a parameterisation of mesoscale eddy-induced turbulence which
+\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.
@@ -1033,10 +1040,10 @@
 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 a advective scheme which is diffusive enough to maintain the model stability.
+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.
-There are not all available in \NEMO. For active tracers (temperature and salinity) the main ones are:
+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.
@@ -1141,5 +1148,5 @@
                          - \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 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)
@@ -1164,5 +1171,5 @@
 a geographical coordinate system \citep{lengaigne.madec.ea_JGR03}.
 
-\subsubsection{lateral bilaplacian momentum diffusive operator}
+\subsubsection{Lateral bilaplacian momentum diffusive operator}
 
 As for tracers, the bilaplacian order momentum diffusive operator is a re-entering Laplacian operator with
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/introduction.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/introduction.tex	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/NEMO/subfiles/introduction.tex	(revision 11353)
@@ -151,5 +151,5 @@
 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:D} and a more complete document is available .
+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.
@@ -158,5 +158,5 @@
 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:D}.      %====>>>> to be done !
+%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/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/SI3/main/routines.idx
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/SI3/main/routines.idx	(revision 11352)
+++ 	(revision )
@@ -1,1 +1,0 @@
-link ../build/routines.idx
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/TOP/main/routines.idx
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/TOP/main/routines.idx	(revision 11352)
+++ 	(revision )
@@ -1,1 +1,0 @@
-link ../build/routines.idx
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/global/annex_D.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/global/annex_D.tex	(revision 11353)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/global/annex_D.tex	(revision 11353)
@@ -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/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/global/coding_rules.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/global/coding_rules.tex	(revision 11353)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/global/coding_rules.tex	(revision 11353)
@@ -0,0 +1,844 @@
+%\documentclass{article}
+
+%\usepackage{fancyhdr}
+%\usepackage{times}
+%\usepackage{graphicx}
+%\usepackage{hyperref}
+%\usepackage{minted}
+%\usepackage[normalem]{ulem}   % striketrough style with \sout{...}
+
+%\hypersetup{pdftitle={NEMO coding conventions}, pdfauthor={NEMO System Team}, colorlinks}
+%\setminted{style=emacs, breaklines, frame=leftline}
+%\newmintinline[forcode]{fortran}{fontsize=auto, frame=lines}   % \forcode{...}
+%\newminted[forlines]{fortran}{}                                % \begin{forlines}
+
+%\pagestyle{empty}
+%\setlength{\leftmargin}{1 cm}
+%\setlength{\rightmargin}{1 cm}
+%\setlength{\oddsidemargin}{0 cm}
+%\setlength{\evensidemargin}{0 cm}
+%\setlength{\topmargin}{-1cm}
+%\setlength{\textwidth}{16 cm}
+%\setlength{\textheight}{25cm}
+%\pagestyle{fancy}
+
+%\title{
+%  \includegraphics[width=0.3\textwidth]{../../../figures/NEMO_grey} \\
+%  \vspace{1.0cm} \rule{345pt}{1.5pt} \\
+%  \vspace{0.45cm} {\Huge NEMO coding conventions} \rule{345pt}{1.5pt} \\
+%}
+%\title{NEMO coding conventions}
+%\author{\Large NEMO System Team
+%  \thanks{
+%    To be completed
+%  }
+%}
+%\date{version X.X -- month year}
+
+%\begin{document}
+
+%\maketitle
+
+%\newpage
+
+%\tableofcontents
+
+%\newpage
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+\chapter{Coding Rules}
+\label{apdx:coding}
+
+\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.
+
+\section{Introduction}
+
+This document describes conventions\index{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\index{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\index{module} 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\index{variable} 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 FORTRAN 95 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} \par & & & & \\
+      \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 hardwired 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\index{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 inlined (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 subdomains 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
+  Labeled \forcode{DO} construct
+  (use unlabeled \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 subprogram 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}
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% \printindex
+% \input NEMO_coding.conv.ind
+
+%\end{document}
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/global/document.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/global/document.tex	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/global/document.tex	(revision 11353)
@@ -85,4 +85,7 @@
 \include{appendices}
 
+%% Append coding rules for every manual
+\input{../../global/coding_rules}
+
 
 %% Backmatter
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/global/highlighting.tex
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/global/highlighting.tex	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/latex/global/highlighting.tex	(revision 11353)
@@ -25,7 +25,7 @@
 
 %% Inline
-\newmintinline[forcode]{fortran}{fontsize=auto, frame=lines}   % \forcode{...}
-\newmintinline[xmlcode]{xml}{    fontsize=auto, frame=lines}   % \xmlcode{...}
-\newmintinline[snippet]{console}{fontsize=auto, frame=lines}   % \snippet{...}
+\newmintinline[forcode]{fortran}{bgcolor=, fontsize=auto, frame=lines}   % \forcode{...}
+\newmintinline[xmlcode]{xml}{    bgcolor=, fontsize=auto, frame=lines}   % \xmlcode{...}
+\newmintinline[snippet]{console}{bgcolor=, fontsize=auto, frame=lines}   % \snippet{...}
 
 %% Namelists inclusion
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/namelists/namdom_domcfg
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/namelists/namdom_domcfg	(revision 11353)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/namelists/namdom_domcfg	(revision 11353)
@@ -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/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/namelists/namobs
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/namelists/namobs	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/namelists/namobs	(revision 11353)
@@ -8,5 +8,5 @@
    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_sss      = .false.             ! Logical switch for SSS observations
    ln_sic      = .false.             ! Logical switch for Sea Ice observations
    ln_vel3d    = .false.             ! Logical switch for velocity observations
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/namelists/namzgr_domcfg
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/namelists/namzgr_domcfg	(revision 11353)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/namelists/namzgr_domcfg	(revision 11353)
@@ -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/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/namelists/namzgr_sco_domcfg
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/namelists/namzgr_sco_domcfg	(revision 11353)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/doc/namelists/namzgr_sco_domcfg	(revision 11353)
@@ -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/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/src/OCE/DYN/dynzdf.F90
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/src/OCE/DYN/dynzdf.F90	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/src/OCE/DYN/dynzdf.F90	(revision 11353)
@@ -170,6 +170,6 @@
                      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 = 0.5_wp * ( wi(ji,jj,jk  ) + wi(ji+1,jj,jk  ) )
-                     zWus = 0.5_wp * ( wi(ji,jj,jk+1) + wi(ji+1,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 )
@@ -185,6 +185,6 @@
                      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 = 0.5_wp * ( wi(ji,jj,jk  ) + wi(ji+1,jj,jk  ) )
-                     zWus = 0.5_wp * ( wi(ji,jj,jk+1) + wi(ji+1,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 )
@@ -199,5 +199,5 @@
                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 = 0.5_wp * ( wi(ji  ,jj,2) +  wi(ji+1,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 ) )
@@ -336,6 +336,6 @@
                      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 = 0.5_wp * ( wi(ji,jj,jk  ) + wi(ji,jj+1,jk  ) ) * wvmask(ji,jj,jk  )
-                     zWvs = 0.5_wp * ( wi(ji,jj,jk+1) + wi(ji,jj+1,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 )
@@ -351,6 +351,6 @@
                      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 = 0.5_wp * ( wi(ji,jj,jk  ) + wi(ji,jj+1,jk  ) ) * wvmask(ji,jj,jk  )
-                     zWvs = 0.5_wp * ( wi(ji,jj,jk+1) + wi(ji,jj+1,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 )
@@ -365,5 +365,5 @@
                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 = 0.5_wp * ( wi(ji,jj  ,2) +  wi(ji,jj+1,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 ) )
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/src/OCE/DYN/sshwzv.F90
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/src/OCE/DYN/sshwzv.F90	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/src/OCE/DYN/sshwzv.F90	(revision 11353)
@@ -284,5 +284,5 @@
       !
       INTEGER  ::   ji, jj, jk   ! dummy loop indices
-      REAL(wp)             ::   zCu, zcff, z1_e3w                     ! local scalars
+      REAL(wp)             ::   zCu, zcff, z1_e3t                     ! local scalars
       REAL(wp) , PARAMETER ::   Cu_min = 0.15_wp                      ! local parameters
       REAL(wp) , PARAMETER ::   Cu_max = 0.27                         ! local parameters
@@ -297,4 +297,5 @@
          IF(lwp) WRITE(numout,*) 'wAimp : Courant number-based partitioning of now vertical velocity '
          IF(lwp) WRITE(numout,*) '~~~~~ '
+         wi(:,:,:) = 0._wp
       ENDIF
       !
@@ -303,13 +304,13 @@
          DO jj = 2, jpjm1
             DO ji = 2, fs_jpim1   ! vector opt.
-               z1_e3w = 1._wp / e3w_n(ji,jj,jk)
-               Cu_adv(ji,jj,jk) = 2._wp * rdt * ( ( MAX( wn(ji,jj,jk) , 0._wp ) - MIN( wn(ji,jj,jk+1) , 0._wp ) )    &  ! 2*rdt and not r2dt (for restartability)
-                  &                             + ( MAX( e2u(ji  ,jj)*e3uw_n(ji  ,jj,jk)*un(ji  ,jj,jk), 0._wp ) -   &
-                  &                                 MIN( e2u(ji-1,jj)*e3uw_n(ji-1,jj,jk)*un(ji-1,jj,jk), 0._wp ) )   &
-                  &                               * r1_e1e2t(ji,jj)                                                  &
-                  &                             + ( MAX( e1v(ji,jj  )*e3vw_n(ji,jj  ,jk)*vn(ji,jj  ,jk), 0._wp ) -   &
-                  &                                 MIN( e1v(ji,jj-1)*e3vw_n(ji,jj-1,jk)*vn(ji,jj-1,jk), 0._wp ) )   &
-                  &                               * r1_e1e2t(ji,jj)                                                  &
-                  &                             ) * z1_e3w
+               z1_e3t = 1._wp / e3t_n(ji,jj,jk)
+               Cu_adv(ji,jj,jk) = 2._wp * rdt * ( ( MAX( wn(ji,jj,jk) , 0._wp ) - MIN( wn(ji,jj,jk+1) , 0._wp ) )   &  ! 2*rdt and not r2dt (for restartability)
+                  &                             + ( 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
@@ -320,9 +321,15 @@
       !
       IF( MAXVAL( Cu_adv(:,:,:) ) > Cu_min ) THEN       ! Quick check if any breaches anywhere
-         DO jk = 1, jpkm1                               ! or scan Courant criterion and partition
+         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) )
+                  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
@@ -343,4 +350,5 @@
             END DO
          END DO
+         Cu_adv(:,:,1) = 0._wp 
       ELSE
          ! Fully explicit everywhere
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/src/OCE/STO/stopar.F90
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/src/OCE/STO/stopar.F90	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/src/OCE/STO/stopar.F90	(revision 11353)
@@ -270,5 +270,5 @@
       IF(lwm) WRITE ( numond, namsto )
 
-      IF( .NOT.ln_rststo ) THEN   ! no use of stochastic parameterization
+      IF( .NOT.ln_sto_eos ) THEN   ! no use of stochastic parameterization
          IF(lwp) THEN
             WRITE(numout,*)
Index: NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/src/OCE/step.F90
===================================================================
--- NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/src/OCE/step.F90	(revision 11352)
+++ NEMO/branches/2019/dev_r10984_HPC-13_IRRMANN_BDY_optimization/src/OCE/step.F90	(revision 11353)
@@ -198,9 +198,11 @@
                             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                         
                             CALL wzv        ( kstp )              ! now cross-level velocity 
          IF( ln_zad_Aimp )  CALL wAimp      ( kstp )  ! Adaptive-implicit vertical advection partitioning
       ENDIF
-      
-                         CALL dyn_zdf       ( kstp )  ! vertical diffusion
 
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
