[cdftools] 04/10: New upstream 3.0.1

Alastair McKinstry mckinstry at moszumanska.debian.org
Sat Jul 29 10:16:26 UTC 2017


This is an automated email from the git hooks/post-receive script.

mckinstry pushed a commit to branch debian/master
in repository cdftools.

commit a9cec1e82395fa524807a0fe103d5239b56c378e
Author: Alastair McKinstry <mckinstry at debian.org>
Date:   Wed Jul 19 12:13:02 2017 +0100

    New upstream 3.0.1
---
 DOC/cdftools.css                                   |   19 +
 DOC/cdftools.html                                  | 4564 ++++++++++++++++++++
 License/CDFTOOLSCeCILL.txt                         |   11 +-
 Macrolib/macro.ada                                 |    7 +-
 Macrolib/macro.curie                               |   12 +-
 Macrolib/macro.ftn_hlrn_nc4                        |   11 +
 Macrolib/macro.gforhp                              |   18 +
 Macrolib/macro.gfortran                            |    8 +-
 Macrolib/macro.gfortran_hlrn                       |   10 +
 Macrolib/macro.gfortran_hlrn_nc4                   |   12 +
 Macrolib/{macro.ifort => macro.hplaptop}           |    9 +-
 Macrolib/macro.ifort                               |    7 +-
 Macrolib/macro.ifort_hlrn_nc4                      |   36 +
 Macrolib/macro.ifort_nesh_fe                       |   16 +
 Macrolib/macro.jade                                |   15 +-
 Macrolib/macro.lgge                                |   19 +
 Macrolib/macro.meolkerg                            |   11 +-
 Macrolib/{macro.curie => macro.occigen}            |   13 +-
 Macrolib/{macro.curie => macro.occigen2}           |   12 +-
 README.md                                          |   86 +
 bin/.gitignore                                     |    2 +
 cdfbuoyflx.f90                                     |  315 --
 cdfchgrid.f90                                      |  213 -
 cdfcurl.f90                                        |  209 -
 cdfdiv.f90                                         |  199 -
 cdfeke.f90                                         |  149 -
 cdffindij.f90                                      |   89 -
 cdfgradT.f90                                       |  216 -
 cdfheatc.f90                                       |  181 -
 cdfmltmask.f90                                     |  178 -
 cdfmoy_freq.f90                                    |  225 -
 cdftools-begin.pod                                 |   21 -
 cdftransport.f90                                   | 1176 -----
 cdfvsig.f90                                        |  292 --
 src/.gitignore                                     |    1 +
 Makefile => src/Makefile                           |  211 +-
 cdf16bit.f90 => src/cdf16bit.f90                   |    0
 cdf2levitusgrid2d.f90 => src/cdf2levitusgrid2d.f90 |    0
 cdf2levitusgrid2d.f90 => src/cdf2levitusgrid3d.f90 |  128 +-
 cdf2matlab.f90 => src/cdf2matlab.f90               |    0
 src/cdf_xtrac_brokenline.f90                       | 1030 +++++
 cdfbathy.f90 => src/cdfbathy.f90                   |   93 +-
 cdfbci.f90 => src/cdfbci.f90                       |    0
 cdfbn2.f90 => src/cdfbn2.f90                       |    0
 cdfbotpressure.f90 => src/cdfbotpressure.f90       |   55 +-
 cdfbottom.f90 => src/cdfbottom.f90                 |    0
 cdfbottomsig.f90 => src/cdfbottomsig.f90           |   25 +-
 cdfbti.f90 => src/cdfbti.f90                       |    0
 src/cdfbuoyflx.f90                                 |  426 ++
 cdfcensus.f90 => src/cdfcensus.f90                 |    0
 src/cdfchgrid.f90                                  |  372 ++
 cdfclip.f90 => src/cdfclip.f90                     |   10 +-
 cdfcmp.f90 => src/cdfcmp.f90                       |    2 +-
 cdfcoastline.f90 => src/cdfcoastline.f90           |    0
 cdfcofdis.f90 => src/cdfcofdis.f90                 |   58 +-
 cdfcoloc.f90 => src/cdfcoloc.f90                   |    0
 cdfconvert.f90 => src/cdfconvert.f90               |    0
 cdfcsp.f90 => src/cdfcsp.f90                       |    0
 src/cdfcurl.f90                                    |  415 ++
 src/cdfdegradt.f90                                 |  321 ++
 src/cdfdegradu.f90                                 |  316 ++
 src/cdfdegradv.f90                                 |  315 ++
 src/cdfdegradw.f90                                 |  314 ++
 cdfdifmask.f90 => src/cdfdifmask.f90               |    1 +
 src/cdfdiv.f90                                     |  404 ++
 src/cdfeddyscale.f90                               |  227 +
 src/cdfeddyscale_pass1.f90                         |  398 ++
 src/cdfeke.f90                                     |  284 ++
 cdfmoyt.f90 => src/cdfenstat.f90                   |  241 +-
 cdfets.f90 => src/cdfets.f90                       |    2 +
 src/cdffindij.f90                                  |  159 +
 cdffixtime.f90 => src/cdffixtime.f90               |    0
 cdfflxconv.f90 => src/cdfflxconv.f90               |    0
 cdffracinv.f90 => src/cdffracinv.f90               |    0
 src/cdffwc.f90                                     |  319 ++
 cdfgeo-uv.f90 => src/cdfgeo-uv.f90                 |  160 +-
 cdfgeostrophy.f90 => src/cdfgeostrophy.f90         |    0
 src/cdfgradT.f90                                   |  280 ++
 cdfhdy.f90 => src/cdfhdy.f90                       |    0
 cdfhdy3d.f90 => src/cdfhdy3d.f90                   |    0
 src/cdfheatc.f90                                   |  298 ++
 cdfhflx.f90 => src/cdfhflx.f90                     |    0
 src/cdfhgradb.f90                                  |  273 ++
 src/cdficb_clim.f90                                |  174 +
 src/cdficb_diags.f90                               |  204 +
 cdficediags.f90 => src/cdficediags.f90             |  141 +-
 cdfimprovechk.f90 => src/cdfimprovechk.f90         |    0
 cdfinfo.f90 => src/cdfinfo.f90                     |   34 +-
 cdfio.f90 => src/cdfio.F90                         |  923 +++-
 src/cdfisf_fill.f90                                |  244 ++
 src/cdfisf_forcing.f90                             |  253 ++
 src/cdfisf_poolchk.f90                             |  213 +
 src/cdfisf_rnf.f90                                 |  316 ++
 cdfisopsi.f90 => src/cdfisopsi.f90                 |    0
 cdfkempemekeepe.f90 => src/cdfkempemekeepe.f90     |    0
 src/cdflap.f90                                     |  322 ++
 cdflinreg.f90 => src/cdflinreg.f90                 |    0
 cdfmaskdmp.f90 => src/cdfmaskdmp.f90               |    2 +-
 cdfmax.f90 => src/cdfmax.f90                       |    1 +
 cdfmaxmoc.f90 => src/cdfmaxmoc.f90                 |    0
 cdfmean.f90 => src/cdfmean.f90                     |   45 +-
 src/cdfmeshmask.f90                                |  845 ++++
 cdfmhst.f90 => src/cdfmhst.f90                     |  252 +-
 cdfmht_gsop.f90 => src/cdfmht_gsop.f90             |    0
 cdfmkmask.f90 => src/cdfmkmask.f90                 |   14 +-
 src/cdfmltmask.f90                                 |  280 ++
 cdfmoc.f90 => src/cdfmoc.f90                       |  400 +-
 cdfmocsig.f90 => src/cdfmocsig.f90                 |  365 +-
 cdfmoy.f90 => src/cdfmoy.f90                       |  217 +-
 src/cdfmoy_freq.f90                                |  367 ++
 cdfmoy_weighted.f90 => src/cdfmoy_weighted.f90     |  128 +-
 cdfmoyt.f90 => src/cdfmoyt.f90                     |    0
 cdfmoyuvwt.f90 => src/cdfmoyuvwt.f90               |    0
 cdfmppini.f90 => src/cdfmppini.f90                 |    4 +-
 cdfmsk.f90 => src/cdfmsk.f90                       |    0
 cdfmxl.f90 => src/cdfmxl.f90                       |   48 +-
 cdfmxlhcsc.f90 => src/cdfmxlhcsc.f90               |    0
 cdfmxlheatc.f90 => src/cdfmxlheatc.f90             |    7 +-
 cdfmxlsaltc.f90 => src/cdfmxlsaltc.f90             |   16 +-
 cdfnamelist.f90 => src/cdfnamelist.f90             |    0
 cdfnan.f90 => src/cdfnan.f90                       |    0
 cdfnorth_unfold.f90 => src/cdfnorth_unfold.f90     |    0
 cdfnrjcomp.f90 => src/cdfnrjcomp.f90               |    0
 cdfokubo-w.f90 => src/cdfokubo-w.f90               |    0
 cdfovide.f90 => src/cdfovide.f90                   |  172 +-
 src/cdfpdf.f90                                     |  262 ++
 cdfpendep.f90 => src/cdfpendep.f90                 |    0
 cdfpolymask.f90 => src/cdfpolymask.f90             |   20 +-
 cdfprobe.f90 => src/cdfprobe.f90                   |    0
 cdfprofile.f90 => src/cdfprofile.f90               |    0
 cdfpsi.f90 => src/cdfpsi.f90                       |   16 +-
 cdfpsi_level.f90 => src/cdfpsi_level.f90           |    0
 cdfpvor.f90 => src/cdfpvor.f90                     |   32 +-
 cdfrhoproj.f90 => src/cdfrhoproj.f90               |  168 +-
 cdfrichardson.f90 => src/cdfrichardson.f90         |    0
 cdfrmsssh.f90 => src/cdfrmsssh.f90                 |   25 +-
 cdfscale.f90 => src/cdfscale.f90                   |    0
 cdfsections.f90 => src/cdfsections.f90             |    6 +-
 cdfsig0.f90 => src/cdfsig0.f90                     |   61 +-
 cdfsigi.f90 => src/cdfsigi.f90                     |    0
 cdfsiginsitu.f90 => src/cdfsiginsitu.f90           |   77 +-
 cdfsigintegr.f90 => src/cdfsigintegr.f90           |    0
 cdfsigintegr.f90 => src/cdfsigintegr_bottom.f90    |  139 +-
 src/cdfsigintegr_pedro.f90                         |  578 +++
 cdfsig0.f90 => src/cdfsigntr.f90                   |   40 +-
 cdfsigtrp.f90 => src/cdfsigtrp.f90                 |  237 +-
 src/cdfsigtrp_broken.f90                           |  883 ++++
 cdfsigtrp.f90 => src/cdfsigtrp_broken2.f90         |  217 +-
 cdfsmooth.f90 => src/cdfsmooth.f90                 |  106 +-
 cdfspeed.f90 => src/cdfspeed.f90                   |   31 +-
 cdfspice.f90 => src/cdfspice.f90                   |  114 +-
 cdfsstconv.f90 => src/cdfsstconv.f90               |    0
 cdfstatcoord.f90 => src/cdfstatcoord.f90           |    0
 cdfstats.f90 => src/cdfstats.f90                   |    0
 cdfstd.f90 => src/cdfstd.f90                       |  147 +-
 cdfstdevts.f90 => src/cdfstdevts.f90               |    0
 cdfstdevw.f90 => src/cdfstdevw.f90                 |   41 +-
 cdfstrconv.f90 => src/cdfstrconv.f90               |    0
 cdfsum.f90 => src/cdfsum.f90                       |  188 +-
 cdftempvol-full.f90 => src/cdftempvol-full.f90     |    0
 src/cdftools-begin.pod                             |   23 +
 cdftools-end.pod => src/cdftools-end.pod           |   10 +-
 cdftools.f90 => src/cdftools.f90                   |  408 +-
 cdftransig_xy3d.f90 => src/cdftransig_xy3d.f90     |    0
 src/cdftransport.f90                               | 1245 ++++++
 cdfvT.f90 => src/cdfuv.f90                         |  148 +-
 cdfvFWov.f90 => src/cdfvFWov.f90                   |    0
 cdfvT.f90 => src/cdfvT.f90                         |   60 +-
 cdfvertmean.f90 => src/cdfvertmean.f90             |  245 +-
 cdfvhst.f90 => src/cdfvhst.f90                     |    0
 cdfvint.f90 => src/cdfvint.f90                     |  111 +-
 cdfvita-geo.f90 => src/cdfvita-geo.f90             |    0
 cdfvita.f90 => src/cdfvita.f90                     |  181 +-
 src/cdfvsig.f90                                    |  579 +++
 cdfvtrp.f90 => src/cdfvtrp.f90                     |    0
 cdfw.f90 => src/cdfw.f90                           |    0
 cdfweight.f90 => src/cdfweight.f90                 |    0
 cdfwflx.f90 => src/cdfwflx.f90                     |    0
 cdfwhereij.f90 => src/cdfwhereij.f90               |    0
 cdfzisot.f90 => src/cdfzisot.f90                   |    3 +-
 cdfzonalmean.f90 => src/cdfzonalmean.f90           |  161 +-
 src/cdfzonalmeanvT.f90                             |  354 ++
 cdfzonalout.f90 => src/cdfzonalout.f90             |    0
 cdfzonalsum.f90 => src/cdfzonalsum.f90             |   99 +-
 cdfzoom.f90 => src/cdfzoom.f90                     |    8 +-
 eos.f90 => src/eos.f90                             |  147 +-
 modcdfnames.f90 => src/modcdfnames.f90             |  200 +-
 modpoly.f90 => src/modpoly.f90                     |    0
 modutils.f90 => src/modutils.f90                   |  209 +
 src/namdom_template_75                             |   45 +
 190 files changed, 23642 insertions(+), 5468 deletions(-)

diff --git a/DOC/cdftools.css b/DOC/cdftools.css
new file mode 100644
index 0000000..90cec1c
--- /dev/null
+++ b/DOC/cdftools.css
@@ -0,0 +1,19 @@
+h1 {
+    color: red;
+    text-align: left;
+   }
+
+h2 {
+    color: blue;
+   }
+
+ul {
+    list-style-type: disc;
+    color: red;
+     }
+
+ul ul li {
+    list-style-type: circle;
+    color: blue;
+     }
+
diff --git a/DOC/cdftools.html b/DOC/cdftools.html
new file mode 100644
index 0000000..bb52194
--- /dev/null
+++ b/DOC/cdftools.html
@@ -0,0 +1,4564 @@
+<?xml version="1.0" ?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<title>CDFTOOLS Man pages</title>
+<link rel="stylesheet" href="./cdftools.css" type="text/css" />
+<meta http-equiv="content-type" content="text/html; charset=utf-8" />
+<link rev="made" href="mailto:root at localhost" />
+</head>
+
+<body>
+
+
+
+<ul id="index">
+  <li><a href="#NAME">NAME</a></li>
+  <li><a href="#PACKAGE-DESCRIPTION">PACKAGE DESCRIPTION</a></li>
+  <li><a href="#SYNOPSIS">SYNOPSIS</a></li>
+  <li><a href="#COMMANDS-DESCRIPTION">COMMANDS DESCRIPTION</a>
+    <ul>
+      <li><a href="#cdf16bit">cdf16bit</a></li>
+      <li><a href="#cdf2levitusgrid2d">cdf2levitusgrid2d</a></li>
+      <li><a href="#cdf2levitusgrid3d">cdf2levitusgrid3d</a></li>
+      <li><a href="#cdf2matlab">cdf2matlab</a></li>
+      <li><a href="#cdf_xtrac_brokenline">cdf_xtrac_brokenline</a></li>
+      <li><a href="#cdfbathy">cdfbathy</a></li>
+      <li><a href="#cdfbci">cdfbci</a></li>
+      <li><a href="#cdfbn2">cdfbn2</a></li>
+      <li><a href="#cdfbotpressure">cdfbotpressure</a></li>
+      <li><a href="#cdfbottom">cdfbottom</a></li>
+      <li><a href="#cdfbottomsig">cdfbottomsig</a></li>
+      <li><a href="#cdfbti">cdfbti</a></li>
+      <li><a href="#cdfbuoyflx">cdfbuoyflx</a></li>
+      <li><a href="#cdfcensus">cdfcensus</a></li>
+      <li><a href="#cdfchgrid">cdfchgrid</a></li>
+      <li><a href="#cdfclip">cdfclip</a></li>
+      <li><a href="#cdfcmp">cdfcmp</a></li>
+      <li><a href="#cdfcofdis">cdfcofdis</a></li>
+      <li><a href="#cdfcoloc">cdfcoloc</a></li>
+      <li><a href="#cdfconvert">cdfconvert</a></li>
+      <li><a href="#cdfcsp">cdfcsp</a></li>
+      <li><a href="#cdfcurl">cdfcurl</a></li>
+      <li><a href="#cdfdegradt">cdfdegradt</a></li>
+      <li><a href="#cdfdegradu">cdfdegradu</a></li>
+      <li><a href="#cdfdegradv">cdfdegradv</a></li>
+      <li><a href="#cdfdegradw">cdfdegradw</a></li>
+      <li><a href="#cdfdifmask">cdfdifmask</a></li>
+      <li><a href="#cdfdiv">cdfdiv</a></li>
+      <li><a href="#cdfeddyscale">cdfeddyscale</a></li>
+      <li><a href="#cdfeddyscale_pass1">cdfeddyscale_pass1</a></li>
+      <li><a href="#cdfeke">cdfeke</a></li>
+      <li><a href="#cdfenstat">cdfenstat</a></li>
+      <li><a href="#cdfets">cdfets</a></li>
+      <li><a href="#cdffindij">cdffindij</a></li>
+      <li><a href="#cdffixtime">cdffixtime</a></li>
+      <li><a href="#cdfflxconv">cdfflxconv</a></li>
+      <li><a href="#cdffracinv">cdffracinv</a></li>
+      <li><a href="#cdffwc">cdffwc</a></li>
+      <li><a href="#cdfgeo-uv">cdfgeo-uv</a></li>
+      <li><a href="#cdfgeostrophy">cdfgeostrophy</a></li>
+      <li><a href="#cdfgradT">cdfgradT</a></li>
+      <li><a href="#cdfhdy">cdfhdy</a></li>
+      <li><a href="#cdfhdy3d">cdfhdy3d</a></li>
+      <li><a href="#cdfheatc">cdfheatc</a></li>
+      <li><a href="#cdfhflx">cdfhflx</a></li>
+      <li><a href="#cdfhgradb">cdfhgradb</a></li>
+      <li><a href="#cdficb_clim">cdficb_clim</a></li>
+      <li><a href="#cdficb_diags">cdficb_diags</a></li>
+      <li><a href="#cdficediags">cdficediags</a></li>
+      <li><a href="#cdfimprovechk">cdfimprovechk</a></li>
+      <li><a href="#cdfinfo">cdfinfo</a></li>
+      <li><a href="#cdfisf_fill">cdfisf_fill</a></li>
+      <li><a href="#cdfisf_forcing">cdfisf_forcing</a></li>
+      <li><a href="#cdfisf_poolchk">cdfisf_poolchk</a></li>
+      <li><a href="#cdfisf_rnf">cdfisf_rnf</a></li>
+      <li><a href="#cdfisopsi">cdfisopsi</a></li>
+      <li><a href="#cdfkempemekeepe">cdfkempemekeepe</a></li>
+      <li><a href="#cdflap">cdflap</a></li>
+      <li><a href="#cdflinreg">cdflinreg</a></li>
+      <li><a href="#cdfmaskdmp">cdfmaskdmp</a></li>
+      <li><a href="#cdfmax">cdfmax</a></li>
+      <li><a href="#cdfmaxmoc">cdfmaxmoc</a></li>
+      <li><a href="#cdfmean">cdfmean</a></li>
+      <li><a href="#cdfmhst">cdfmhst</a></li>
+      <li><a href="#cdfmkmask">cdfmkmask</a></li>
+      <li><a href="#cdfmltmask">cdfmltmask</a></li>
+      <li><a href="#cdfmoc">cdfmoc</a></li>
+      <li><a href="#cdfmocsig">cdfmocsig</a></li>
+      <li><a href="#cdfmoy">cdfmoy</a></li>
+      <li><a href="#cdfmoy_freq">cdfmoy_freq</a></li>
+      <li><a href="#cdfmoy_weighted">cdfmoy_weighted</a></li>
+      <li><a href="#cdfmoyt">cdfmoyt</a></li>
+      <li><a href="#cdfmoyuvwt">cdfmoyuvwt</a></li>
+      <li><a href="#cdfmppini">cdfmppini</a></li>
+      <li><a href="#cdfmxl">cdfmxl</a></li>
+      <li><a href="#cdfmxlhcsc">cdfmxlhcsc</a></li>
+      <li><a href="#cdfmxlheatc">cdfmxlheatc</a></li>
+      <li><a href="#cdfmxlsaltc">cdfmxlsaltc</a></li>
+      <li><a href="#cdfnamelist">cdfnamelist</a></li>
+      <li><a href="#cdfnan">cdfnan</a></li>
+      <li><a href="#cdfnorth_unfold">cdfnorth_unfold</a></li>
+      <li><a href="#cdfnrjcomp">cdfnrjcomp</a></li>
+      <li><a href="#cdfokubo-w">cdfokubo-w</a></li>
+      <li><a href="#cdfovide">cdfovide</a></li>
+      <li><a href="#cdfpendep">cdfpendep</a></li>
+      <li><a href="#cdfpolymask">cdfpolymask</a></li>
+      <li><a href="#cdfprobe">cdfprobe</a></li>
+      <li><a href="#cdfprofile">cdfprofile</a></li>
+      <li><a href="#cdfpsi">cdfpsi</a></li>
+      <li><a href="#cdfpsi_level">cdfpsi_level</a></li>
+      <li><a href="#cdfpvor">cdfpvor</a></li>
+      <li><a href="#cdfrhoproj">cdfrhoproj</a></li>
+      <li><a href="#cdfrichardson">cdfrichardson</a></li>
+      <li><a href="#cdfrmsssh">cdfrmsssh</a></li>
+      <li><a href="#cdfscale">cdfscale</a></li>
+      <li><a href="#cdfsections">cdfsections</a></li>
+      <li><a href="#cdfsig0">cdfsig0</a></li>
+      <li><a href="#cdfsigi">cdfsigi</a></li>
+      <li><a href="#cdfsiginsitu">cdfsiginsitu</a></li>
+      <li><a href="#cdfsigintegr">cdfsigintegr</a></li>
+      <li><a href="#cdfsigntr">cdfsigntr</a></li>
+      <li><a href="#cdfsigtrp">cdfsigtrp</a></li>
+      <li><a href="#cdfsigtrp_broken">cdfsigtrp_broken</a></li>
+      <li><a href="#cdfsmooth">cdfsmooth</a></li>
+      <li><a href="#cdfspeed">cdfspeed</a></li>
+      <li><a href="#cdfspice">cdfspice</a></li>
+      <li><a href="#cdfsstconv">cdfsstconv</a></li>
+      <li><a href="#cdfstatcoord">cdfstatcoord</a></li>
+      <li><a href="#cdfstats">cdfstats</a></li>
+      <li><a href="#cdfstd">cdfstd</a></li>
+      <li><a href="#cdfstdevts">cdfstdevts</a></li>
+      <li><a href="#cdfstdevw">cdfstdevw</a></li>
+      <li><a href="#cdfstrconv">cdfstrconv</a></li>
+      <li><a href="#cdfsum">cdfsum</a></li>
+      <li><a href="#cdftempvol-full">cdftempvol-full</a></li>
+      <li><a href="#cdftransport">cdftransport</a></li>
+      <li><a href="#cdfuv">cdfuv</a></li>
+      <li><a href="#cdfvFWov">cdfvFWov</a></li>
+      <li><a href="#cdfvT">cdfvT</a></li>
+      <li><a href="#cdfvar">cdfvar</a></li>
+      <li><a href="#cdfvertmean">cdfvertmean</a></li>
+      <li><a href="#cdfvhst">cdfvhst</a></li>
+      <li><a href="#cdfvint">cdfvint</a></li>
+      <li><a href="#cdfvita">cdfvita</a></li>
+      <li><a href="#cdfvita-geo">cdfvita-geo</a></li>
+      <li><a href="#cdfvsig">cdfvsig</a></li>
+      <li><a href="#cdfvtrp">cdfvtrp</a></li>
+      <li><a href="#cdfw">cdfw</a></li>
+      <li><a href="#cdfweight">cdfweight</a></li>
+      <li><a href="#cdfwflx">cdfwflx</a></li>
+      <li><a href="#cdfwhereij">cdfwhereij</a></li>
+      <li><a href="#cdfzisot">cdfzisot</a></li>
+      <li><a href="#cdfzonalmean">cdfzonalmean</a></li>
+      <li><a href="#cdfzonalmeanvT">cdfzonalmeanvT</a></li>
+      <li><a href="#cdfzonalout">cdfzonalout</a></li>
+      <li><a href="#cdfzonalsum">cdfzonalsum</a></li>
+      <li><a href="#cdfzoom">cdfzoom</a></li>
+    </ul>
+  </li>
+  <li><a href="#AUTHORS">AUTHORS</a></li>
+  <li><a href="#LICENSE-AND-COPYRIGHT">LICENSE AND COPYRIGHT</a></li>
+</ul>
+
+<h1 id="NAME">NAME</h1>
+
+<p>CDFTOOLS - diagnostics in Fortran 90 for NEMO model outputs</p>
+
+<h1 id="PACKAGE-DESCRIPTION">PACKAGE DESCRIPTION</h1>
+
+<p><code>CDFTOOLS</code> is a diagnostic package written in fortran 90 for the analysis of NEMO model output, initialized in the frame of the DRAKKAR project (https://www.drakkar-ocean.eu/). It is now available on GitHub under the CeCILL license (http://www.cecill.info/licences/Licence_CeCILL_V2-en.html).</p>
+
+<p><code>NEMO</code> web site : http://www.nemo-ocean.eu/</p>
+
+<h1 id="SYNOPSIS">SYNOPSIS</h1>
+
+<p><code>CDFTOOLS</code> is a collection of fortran program. Each program belonging to this collection is designed to perform some specific actions on NEMO output files, and generally provides another netcdf file as output. Output files follow the same CDF format as NEMO file, thus allowing for the building of a secondary data base (assuming that the primary data base is just the raw model output).</p>
+
+<p>This documentation is automatically produced by the concatenation of the <code>USAGE</code> messages produced by each particular program when invoked without any argument. (Standard behaviour of all cdftools). In the documentation, we use a rather classical formalism, where mandatory arguments are just indicated on the command line and options are indicated between squared brackets [..].</p>
+
+<p>Each program name starts with the 3 letters 'cdf' followed by a word related to the action performed by the tools. Example: <code>cdfw Ufile.nc Vfile.nc </code> is used to compute the vertical velocity using the horizontal velocity field represented by its two components Ufile.nc and Vfile.nc.</p>
+
+<p>Better than a long speech, the following paragraphs describes each of the existing cdftools.</p>
+
+<h1 id="COMMANDS-DESCRIPTION">COMMANDS DESCRIPTION</h1>
+
+<h2 id="cdf16bit">cdf16bit</h2>
+
+<pre><code>  usage : cdf16bit 32BIT-file [ -check ] [ -verbose]
+       
+      PURPOSE :
+        Convert input 32 bit precision file into 16 bit
+        precision file using add_offset and scale_factor
+       
+      ARGUMENTS :
+        32BIT-file : input 32 bit file to be converted
+       
+      OPTIONS :
+        [ -check ]   : control than the scale factors are adequate
+        [ -verbose ] : give information level by level.
+       
+      REQUIRED FILES :
+        none 
+       
+      OUTPUT : 
+        netcdf file : cdf16bit.nc
+          variables : same names than in input file</code></pre>
+
+<h2 id="cdf2levitusgrid2d">cdf2levitusgrid2d</h2>
+
+<pre><code>  usage : cdf2levitusgrid2d IN-file OUT-file  VAR-name2D
+       
+      PURPOSE :
+        remaps (bin) 2D high resolution (finer than 1x1 deg) 
+        fields on Levitus 2D 1x1 deg grid                    
+        (does not work for vector fields)  
+        It assumes that Levitus grid SW grid cell center 
+        is (0.5W,89.5S) 
+       
+      ARGUMENTS :
+        IN-file  : netcdf input file 
+        OUT-file : netcdf output file 
+        VAR-name2D : input variable name for interpolation 
+       
+      OPTIONS :
+       
+      REQUIRED FILES :
+        mesh_hgr.nc
+        mask.nc
+        levitus_mask.nc
+       
+      OUTPUT : 
+        netcdf file : name given as second argument
+          variables : 2d_var_name</code></pre>
+
+<h2 id="cdf2levitusgrid3d">cdf2levitusgrid3d</h2>
+
+<pre><code>  usage : cdf2levitusgrid3d -f IN-file -o OUT-file  -v VAR-name3D [-360]
+         [-r resolution] 
+       
+      PURPOSE :
+        remaps (bin) 3D high resolution (finer than 1x1 deg) 
+        fields on a regular grid. (vertical grid as input grid)  
+        (does not work for vector fields)  
+        Resolution can be given as argument, default is   0.3333333      deg.
+       
+      ARGUMENTS :
+        -f IN-file  : netcdf input file 
+        -o OUT-file : netcdf output file 
+        -v VAR-name2D : input variable name for interpolation 
+       
+      OPTIONS :
+        -360 : outfile is defined from 0 to 360 deg
+               Default is from -180 to 180 
+        -r  : resolution.
+      
+      REQUIRED FILES :
+        mesh_hgr.nc
+        mask.nc
+       
+      OUTPUT : 
+        netcdf file : name given as second argument
+          variables : 3d_var_name</code></pre>
+
+<h2 id="cdf2matlab">cdf2matlab</h2>
+
+<pre><code>  usage : cdf2matlab IN-file IN-var level 
+       
+      PURPOSE :
+        Convert global nemo input file (ORCA configurations) into
+        a file with monotonically increasing longitudes.
+       
+      ARGUMENTS :
+        IN-file : input model file.
+        IN-var  : netcdf variable name to process.
+        level   : level to process.
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        netcdf file : output.nc
+          variables : same name than in input file.</code></pre>
+
+<h2 id="cdf_xtrac_brokenline">cdf_xtrac_brokenline</h2>
+
+<pre><code>  usage :  cdf_xtrac_brokenline T-file U-file V-file [ice-file] ....
+     [-f section_filei,sec_file2, ... ] [-verbose] [-ssh ] [-mld] [-ice] 
+     [-vt] [-o ROOT_name]
+       
+      PURPOSE :
+         This tool extracts model variables from model files for a geographical
+       broken line, similar to an oceanographic campaign where an oceanic 
+       section is formed by one or more legs.
+         The broken line is specified by the position of ending points of each
+       leg, given in an ASCII file. OVIDE section is taken as default, when no
+       section file is provided.
+         This tool provides a netcdf file similar to a model file, but with a 
+       degenerated y dimension (1). In order to be able to use standard CDFTOOLS
+       relevant metric variables are saved into the output file, such as pseudo
+       e1v and e3v_ps and vmask. Therefore the output file can be considered as
+       a mesh_hgr, mesh_zgr and mask file for any 'meridional' computation.
+         This tools works with temperatures, salinities and normal velocities.
+       The broken line is approximated in the model, by a succession of segments
+       joining F-points. The velocity is taken as either U or V depending on the
+       orientation of the segment, temperatures and salinities are interpolated
+       on the velocity points. When progressing along the broken line, velocity
+       is positive when heading to the right of the progression.
+         The barotropic transport across the broken line is computed, using the
+       same sign convention. On a closed broken line, the barotropic transport
+       should be very small.
+       
+      ARGUMENTS :
+       T-file   :  model gridT file 
+       U-file   :  model gridU file 
+       V-file   :  model gridV file 
+       ice-file :  model ice file 
+       
+      OPTIONS :
+       -f section_file1,section_file2,... : provide a comma separated list of
+               files for section definition. Section_file is an ascii file as 
+               follows:
+              * line #1 : name of the section (e.g. ovide). 
+                   Will be used for naming the output file.
+              * line #2 : number of points defining the broken line.
+              * line #3-end : a pair of Longitude latitude values defining
+                    the points. If not supplied, use hard-coded information
+                    for OVIDE section. A comment can be added at the end of
+                    of the lines, using a # as separator
+       -verbose : increase verbosity  
+       -ssh     : also save ssh along the broken line.
+       -mld     : also save mld along the broken line.
+       -ice     : also save ice properties along the broken line.
+       -vt      : also save products vt and vs along the broken line.
+       -o ROOT-name : specified the prefix to be used for the output file name.
+                  Note that it may be a good idea to include a separator 
+                  character such as _ at the end of the ROOT_name.
+      
+      REQUIRED FILES :
+       mesh_hgr.nc and mesh_zgr.nc in the current directory 
+       
+      OUTPUT : 
+        netcdf file : <section_name>.nc (default). If -o option is used, the
+                      name will be <ROOT-name><section_name>.nc
+          variables : temperature, salinity, normal velocity, pseudo V metrics,
+                     mask, barotropic transport, bathymetry of velocity points.
+                     Additional variables can be set when using options.
+        ASCII file : <section_name>_section.dat usefull for cdftransport, gives
+                   the position in I,J of the geographical input points.
+       
+      SEE ALSO :
+         cdftransport, cdfmoc, cdfmocsig. This tool replaces cdfovide.
+       </code></pre>
+
+<h2 id="cdfbathy">cdfbathy</h2>
+
+<pre><code>  usage : cdfbathy/cdfvar -f IN-file [options]
+       
+      PURPOSE :
+        Allow manual modification of the input file. Very convenient
+        for bathymetric files, can also be used with any model file
+        Keep a log.f90 file of the modifications for automatic reprocessing
+       
+      ARGUMENTS :
+        IN-file : original input file. The program works on a copy of the
+                 original file (default)
+       
+      OPTIONS :
+        -file (or -f )       : name of input file 
+        -var  (or -v )       : name of cdf variable [default: Bathymetry]
+        -lev  (or -l )       : level to work with 
+        -time (or -t )       : time to work with 
+        -scale  s            : use s as a scale factor (divide when read the file)
+        -zoom (or -z )       : sub area of the bathy file to work with (imin imax jmin jmax)
+        -fillzone (or -fz )  : sub area will be filled with 0 up to the first coast line 
+        -fillpool (or -fp ) [ icrit ] : the whole file is check and fill all the pool smaller than (icrit) cell by 0
+        -raz_zone (or -raz ) : sub area will be filled with 0 up 
+        -raz_below depmin    : any depth less than depmin in subarea will be replaced by 0 
+           (or -rb depmin )  
+        -set_below depmin    : any depth less than depmin in subarea will be replaced by depmin 
+           (or -sb depmin ) 
+        -fullstep depmin     : sub area will be reshaped as full-step, below depmin
+           (or -fs depmin )    requires the presence of the file zgr_bat.txt (from ocean.output, eg )
+        -dumpzone (or -d )   : sub area will be output to an ascii file, which can be used by -replace
+                               after manual editing 
+        -nicedumpzone        : sub area will be output to an ascii file (nice output)
+                 (or -nd )
+        -replace (or -r )    : sub area defined by the file will replace the original bathy
+        -append (or -a )     : fortran log file (log.f90) will be append with actual modif
+                               Standard behaviour is to overwrite/create log file
+        -overwrite (or -o )  : input bathy file will be used as output.
+                               Standard behaviour is to use a work copy of the original file
+                               (indexed from 01 to 99 if necessary ) 
+        -log logfile         : log file for change (default is log.f90) 
+       
+      OUTPUT : 
+           netcdf file : according to used options, if the original file is to be modified
+                  a sequence number is added at the end of the input file name, to keep
+                  modifications.
+             variables : same as input file</code></pre>
+
+<h2 id="cdfbci">cdfbci</h2>
+
+<pre><code>  usage : cdfbci UVWT-file
+       
+      PURPOSE :
+        Compute elements for analysing the baroclinic instability
+       
+      ARGUMENTS :
+        UVWT-file : input file is produced by cdfmoyuvwt, and the mean
+               must be computed on a long-enough period for the 
+               statistics to be meaningful. Points are on T grid.
+       
+      REQUIRED FILES :
+        Need mesh_hgr.nc file
+       
+      OUTPUT : 
+        netcdf file : bci.nc
+          variables : 5 output variables
+              dTdx : zonal derivative of Tbar on T point (*1000)
+              dTdy : meridional derivative of Tbar on T point (*1000)
+              uT   : anomaly of u times anomaly of T on T point
+              vT   : anomaly of v times anomaly of T on T point
+              bci  : transfert of energy for the baroclinic instability (*1000)
+       
+      SEE ALSO :
+        cdfmoyuvwt </code></pre>
+
+<h2 id="cdfbn2">cdfbn2</h2>
+
+<pre><code>  usage : cdfbn2  T-file [W] [-full]
+      PURPOSE :
+        Compute the Brunt-Vaissala frequency (N2) according to
+        temperature and salinity given in the input file.
+       
+      ARGUMENTS :
+        T-file : netcdf input gridT file for temperature and salinity.
+       
+      OPTIONS :
+        [ W ] : keep N2 at W points. Default is to interpolate N2
+              at T point on the vertical.
+        [ -full ] : indicate a full step configuration instead of
+                 the default partial steps.
+       
+      REQUIRED FILES :
+        mesh_zgr.nc is needed for this program.
+       
+      OUTPUT : 
+        netcdf file : bn2.nc
+          variables : vobn2</code></pre>
+
+<h2 id="cdfbotpressure">cdfbotpressure</h2>
+
+<pre><code>  usage : cdfbotpressure T-file [-full] [-ssh] [-ssh2 ] [-xtra ] 
+       
+      PURPOSE :
+           Compute the vertical bottom pressure (pa) from in situ density
+       
+      ARGUMENTS :
+          T-file : gridT file holding either Temperature and  salinity 
+       
+      OPTIONS :
+         -full : for full step computation 
+         -ssh  : Also take SSH into account in the computation
+                 In this case, use rau0=   1035.000      kg/m3 for 
+                 surface density (as in NEMO)
+                 If you want to use 2d surface density from 
+                 the model, use option -ssh2
+         -ssh2 : as option -ssh but surface density is taken from 
+                 the model instead of a constant
+         -xtra :  Using this option, the output file also contains the ssh,
+                 and the pressure contribution of ssh to bottom pressure. 
+                 Require either -ssh or -ssh2 option. Botpressure is still
+                 the total pressure, including ssh effect.
+       
+      REQUIRED FILES :
+        mask.nc and mesh_zgr.nc
+       
+      OUTPUT : 
+        netcdf file :  botpressure.nc
+          variables :  sobotpres
+       
+      SEE ALSO :
+         cdfvint
+       </code></pre>
+
+<h2 id="cdfbottom">cdfbottom</h2>
+
+<pre><code>  usage : cdfbottom  IN-file [ T | U | V | F]
+       
+      PURPOSE :
+        Create a 2D file with bottom most values for all the variables
+        which are in the input 3D file.
+       
+      ARGUMENTS :
+        IN-file : input netcdf 3D file.
+       
+      OPTIONS :
+        [ T | U | V | F] : specify the type of grid point on the C-grid
+             if not given, assume that land points are values with 0.
+       
+      REQUIRED FILES :
+        mask.nc file is required if the grid point is specified
+                   or if the land value is not 0.
+       
+      OUTPUT : 
+        netcdf file : bottom.nc
+          variables :  same names than input file, long_name attribute is
+                prefixed by Bottom </code></pre>
+
+<h2 id="cdfbottomsig">cdfbottomsig</h2>
+
+<pre><code>  usage : cdfbottomsig  T-file [zref]
+       
+      PURPOSE :
+        Create a 2D file with bottom density. In case a depth reference
+        is given, the density is refered to this depth. By default sigma-0
+        is used. Bottom most point is determined from the last non zero 
+        salinity point in the water column.
+       
+      ARGUMENTS :
+        T-file : input file with temperature and salinity 
+       
+      OPTIONS :
+        [zref] : depth reference for potential density
+               keyword 'ntr' can also be specified, which indicates that we
+               will use neutral density
+              If not given assume sigma-0
+       
+      REQUIRED FILES :
+        none
+       
+      OUTPUT : 
+        netcdf file : botsig.nc
+          variables : sobotsig0 or sobotsigi ( kg/m3 - 1000 )
+                      or sobotsigntr (kg/m3)</code></pre>
+
+<h2 id="cdfbti">cdfbti</h2>
+
+<pre><code>  usage : cdfbti UVWT-file
+       
+      PURPOSE :
+        Compute  the terms in the barotropic energy tranfert equation.
+        The transfert of energy for the barotropic instability is 
+        bti= -[(u'bar)^2*dubar/dx ...
+              +(v'bar)^2*dvbar/dy ...
+              +(u'v'*(dubar/dy +dvbar/dx))]
+       
+      ARGUMENTS :
+        UVWT-file : netcdf file produced by cdfmoyuvwt
+       
+      REQUIRED FILES :
+        mesh_hgr.nc
+       
+      OUTPUT : 
+        netcdf file : bti.nc
+          variables : 
+                dudx : zonal derivate of ubar on T point
+                dvdx : zonal derivate of vbar on T point
+                dudy : meridional derivate of ubar on T point
+                dvdy : meridional derivate of vbar on T point
+                anousqrt : mean of (u-ubar)^2 on T point
+                anovsqrt : mean of (v-vbar)^2 on T point
+                anouv : mean of (u-ubar)*(v-vbar) on T point
+                bti  : transfert of energy for the barotropic instability.
+       
+      SEE ALSO :
+       cdfmoyuvwt, cdfbci, cdfnrjcomp, cdfkempemekeepe
+       </code></pre>
+
+<h2 id="cdfbuoyflx">cdfbuoyflx</h2>
+
+<pre><code>  usage : cdfbuoyflx  -t T-file [-r RNF-file] [-f FLX-file ] [-sss SSS-name]
+      ... [-sst SST-name] [-nc4] [-o output_file]  [-short ]
+       
+      PURPOSE :
+        Compute (or read) the heat and water fluxes components.
+        Compute (or read) the net heat and water fluxes.
+        Compute the buoyancy heat and water fluxes components.
+        Compute the net buoyancy fluxes.
+        Save sss and sst. 
+       
+      ARGUMENTS :
+        -t T-file   : netcdf file with temperature and salinity 
+       
+       
+      OPTIONS :
+        [ -r RNF-file ] : Specify a run-off file if runoff not in T-file 
+                          nor in FLX-file
+        [ -f FLX-file ] : Use this option if fluxes are not saved in gridT files
+        [ -sss SSS-name ] : Use this option if SSS variable name in T-file 
+                           differ from vosaline
+        [ -sst SST-name ] : Use this option if SST variable name in T-file 
+                           differ from votemper
+        [ -nc4 ] Use netcdf4 output with chunking and deflation level 1
+                This option is effective only if cdftools are compiled with
+                a netcdf library supporting chunking and deflation.
+        [ -o output_file ] Default is buoyflx.nc
+        [ -short ] With this option only save the buoyancy flux without 
+                   all the components of the flux.
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        netcdf file : buoyflx.nc
+          variables : 25 variables (2D) or 1 variable in case of -short option
+       
+      SEE ALSO :
+       
+       </code></pre>
+
+<h2 id="cdfcensus">cdfcensus</h2>
+
+<pre><code>  usage :  cdfcensus T-file nlog [-zoom imin imax jmin jmax] ...
+                 ... [-klim kmin kmax]  [-full] [-bimg] ... 
+                 ... [-srange smin smax ds ] ...
+                 ... [-trange tmin tmax dt ] 
+       
+      PURPOSE :
+         Compute the volumetric water mass census: the ocean is divided in
+         T,S bins; the program gives the volume of water for each bin.
+         A sub-area can be specified, both horizontaly and vertically.
+         Temperature and salinity ranges can be also adapted, as well as the
+         width of the bins. Default values are provided. In order to attenuate
+         the huge maximum values, a log10 operator can be applied many times,
+         the number of filter passes being set on the command line.
+       
+      ARGUMENTS :
+        T-file  : netcdf file name for temperature and salinity
+        nlog    : number of log10 filter to perform. Can be 0.
+       
+      OPTIONS :
+        [-zoom imin imax jmin jmax] : define a model sub-area, in model 
+                                      coordinates
+        [-klim ik1 ik2            ] : set limits on the vertical.
+        [-srange smin smax ds     ] : define the size of the salinity bin
+                         defaut is : 25.0 40.0  0.020
+        [-trange tmin tmax dt     ] : define the size of the temperatude bin
+                         defaut is : -2.0 38.0  0.050
+        [-full                    ] : use for full step computation
+        [-bimg                    ] : output on bimg files (to be deprecated).
+       
+      REQUIRED FILES :
+        mesh_hgr.nc  and mesh_zgr.nc
+       
+      OUTPUT : 
+        - netcdf file : census.nc
+            variables : volcensus  (10^15 m3 )
+                        sigma0  (kg/m3 -1000 )
+                        sigma2  (kg/m3 -1000 )
+                        sigma3  (kg/m3 -1000 )
+        - bimg file   : According to options.</code></pre>
+
+<h2 id="cdfchgrid">cdfchgrid</h2>
+
+<pre><code>  usage : cdfchgrid -f IN-file -r REF-file -var IN-var [-nc4] [-o OUT-file] [-d]
+       
+      PURPOSE :
+        Build a new file on a refined grid, from a coarser grid, assuming that
+        the two grids are embedded, with common points (hence an odd scaling 
+        factor). Grid characteristics are hard wired in the code. Support for
+        ORCA025 --> ORCA12, eORCA025 --> eORCA12 is actually provided. Hooks 
+        are ready in the code for adding new conversion.
+        No interpolation, only copying value of a coarse grid cell, onto 
+        scale x scale cells of the output grid (scale is the refinement factor)
+       
+      RESTRICTION :
+        Caution for mask coherence !
+        This tool is only adapted for drowned field
+       
+      ARGUMENTS :
+        -f IN-file  : input Coarser-grid file
+        -r REF-file : Reference file used for identification of the output grid
+                should be of same geometry than the output file.
+        -var IN-var : input coarser-grid variable to be converted
+       
+      OPTIONS :
+        -nc4        : use netcdf4 chunking and deflation for the output file
+        -o OUT-file : specify output file name instead of cdfchgrid.nc
+        -d          : Display some debugging information 
+       
+      REQUIRED FILES :
+        none 
+       
+      OUTPUT : 
+        netcdf file : cdfchgrid.nc
+          variable : same name as in input file</code></pre>
+
+<h2 id="cdfclip">cdfclip</h2>
+
+<pre><code>  usage : cdfclip -f IN-file [-o OUT-file] -zoom imin imax jmin jmax [kmin kmax]
+       
+      PURPOSE :
+        Clip the input file according to the indices given in the
+        zoom statement. If no vertical zoomed area is indicated, 
+        the whole water column is considered.  This program is able
+        to extract data for a region crossing the E-W periodic boundary
+        of a global configuration. It does so if imax < imin.
+       
+      ARGUMENTS :
+        -f IN-file : specify the input file to be clipped
+        -zoom imin imax jmin jmax : specify the domain to be extracted.
+            If imin=imax, or jmin = jmax assume a vertical section either 
+            meridional or zonal.
+       
+      OPTIONS :
+        [-o OUT-file ] : use OUT-file instead of cdfclip.nc for output file
+                If used, -o option must be used before -zoom argument 
+        [kmin kmax ] : specify vertical limits for the zoom, in order to reduce
+                the extracted area to some levels. Default is to take the whole
+                water column.
+       
+      REQUIRED FILES :
+        none
+       
+      OUTPUT : 
+        netcdf file : cdfclip.nc This can be changed using -o option
+          variables : same as input variables.</code></pre>
+
+<h2 id="cdfcmp">cdfcmp</h2>
+
+<pre><code>  usage : cmp_var -f1 IN-file1 -f2 IN-file2 -var IN-var ...
+      ... [-lev kmin kmax ] [-zoom imin imax jmin jmax] ...
+       
+      PURPOSE :
+         Find where IN-var is different between IN-file1 and IN-file2 
+         Options allow to restrict the finding to a sub area in space
+       
+      ARGUMENTS :
+        -f1 IN-file1 : input file1
+        -f2 IN-file2 : input file2
+        -var IN-var  : input variable
+       
+      OPTIONS :
+        [-lev kmin kmax ] : restrict to level between kmin and kmax. 
+        [-zoom imin imax jmin jmax] : restrict to sub area specified
+                                      by the given limits. 
+       
+      REQUIRED FILES :
+        none 
+       
+      OUTPUT : 
+        output is done on standard output.</code></pre>
+
+<h2 id="cdfcofdis">cdfcofdis</h2>
+
+<pre><code>  usage :  cdfcofdis mesh_hgr.nc mask.nc gridT.nc [-jperio jperio ] [-surf]
+       
+      PURPOSE :
+         Compute the distance to the coast and create a file with the Tcoast
+         variable, indicating the distance to the coast. This computation is don
+ e
+         for every model level, unless -surf option is used.
+       
+      ARGUMENTS :
+        HGR-file : name of the mesh_hgr file 
+        MSK-file : name of the mask file 
+        T-file   : netcdf file at T point.
+       
+      OPTIONS :
+        [ -jperio jperio ] : define the NEMO jperio variable for north fold 
+            condition. Default is  4.
+        [ -surf ] : only compute  distance at the surface.
+       
+      REQUIRED FILES :
+        none
+       
+      OUTPUT : 
+        netcdf file : dist.coast
+          variables : Tcoast (m)
+       
+       </code></pre>
+
+<h2 id="cdfcoloc">cdfcoloc</h2>
+
+<pre><code>  usage : cdfcoloc  -w root_weight -t gridT -trc TRC_file ...
+           ...  -u gridU -v gridV [-l field list ] [-h]
+        -w root_weight  : specify the root name of the weight files
+                          _T.bin, _U.bin, or _V.bin will be appended 
+                          to name if necessary.
+        -t gridT file   : name of gridT model file
+        -trc TRC file   : name of gridT model file
+        -d  diag file   : name of specific diagnostic file 
+        -u gridU file   : name of gridU model file
+        -v gridV file   : name of gridV model file
+        -b bathy file   : name of etopo like bathymetric file
+        -l field list   : list of fields to be colocated, separated by ','
+                          Default list is :U,V,Sx,Sy,H
+        -h              : Give the details of available field to colocate.
+      Return a column ascii file id dep fields()
+ mask.nc is required in local directory
+ coordinates.nc,mesh_zgr.nc are also required for slope computation</code></pre>
+
+<h2 id="cdfconvert">cdfconvert</h2>
+
+<pre><code>  usage : cdfconvert CLIPPER_tag CLIPPER_Confcase
+       
+      PURPOSE :
+        Convert dimg files (CLIPPER like) to netcdf (DRAKKAR like).
+       
+      ARGUMENTS :
+        CLIPPER_tag      : a string such as y2000m01d15 for time identification.
+        CLIPPER_confcase : CONFIG-CASE of the files to be converted (eg ATL6-V6)
+       
+      REQUIRED FILES :
+         mesh_hgr.nc and mesh_zgr.nc
+       
+      OUTPUT : 
+        netcdf file : gridT, gridU, gridV files
+          variables : same as in standard NEMO output
+       
+      SEE ALSO :
+        cdfflxconv, cdfsstconv, cdfstrconv
+       </code></pre>
+
+<h2 id="cdfcsp">cdfcsp</h2>
+
+<pre><code>  usage : cdfcsp list_of_files 
+       
+      PURPOSE :
+        Replace missing_values by 0 and update attribute
+       
+      ARGUMENTS :
+        The list of cdf file to process, all variables will be processed
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        netcdf file : same as input file (modified)
+          variables : same as input file</code></pre>
+
+<h2 id="cdfcurl">cdfcurl</h2>
+
+<pre><code>  usage : cdfcurl -u U-file U-var -v V-file V-var -l levlist [-T] [-8]...
+            ... [-surf] [-overf] [-nc4] [-o OUT-file ]
+       
+      PURPOSE :
+        Compute the curl of a vector field, at a specified level.
+        If level is specified as 0, assume that the input files are
+        forcing files, presumably on A-grid. In this latter case, the
+        vector field is interpolated on the C-grid. In any case, the
+        curl is computed on the F-point (unless -T option is used).
+       
+      ARGUMENTS :
+        -u U-file U-var : file and variable name for zonal component
+        -v V-file V-var : file and variable name for meridional component
+        -l levlist    : levels to be processed. If set to 0, assume forcing file
+                 in input. Example of recognized syntax :
+                   -l "1,10,30"  or -l "1-20" or even -l "1-3,10-20,30-"
+                   -l  1 . Note that -l "3-" set a levlist from 3 to the bottom
+ 
+      OPTIONS :
+        -T : compute curl at T point instead of default F-point
+        -8 : save in double precision instead of standard simple precision.
+        -surf : work with single level C-grid (not forcing)
+        -overf : store the ratio curl/f where f is the coriolis parameter
+        -nc4 : use netcdf4 output with chunking and deflation 1
+        -o OUT-file : specify output file name instead of curl.nc
+       
+      REQUIRED FILES :
+         mesh_hgr.nc
+       
+      OUTPUT : 
+        netcdf file : curl.nc
+          variables : socurl or socurlt (if -T option), units : s^-1
+             or socurloverf, no units (if -overf option)</code></pre>
+
+<h2 id="cdfdegradt">cdfdegradt</h2>
+
+<pre><code>  usage : cdfdegradt IN-Tfile IN-var ri rj [i0 j0]
+        ... [-full]
+        
+      PURPOSE :
+        Degrad the horizontal resolution of NEMO T-grid ouput,       
+        for each z-level and time step, with a ratio of ri along     
+        x direction and rj along y direction. If specified, the input
+        grid is considered starting from the indices i0 and j0.      
+       
+      ARGUMENTS :
+        IN-Tfile  : netcdf T-file.
+        IN-var    : name of netcdf variable to work with
+        ri        : degradation ratio for x-direction   
+        rj        : degradation ratio for y-direction   
+       
+      OPTIONS : 
+        [i0 j0] : spatial indices from where starting the procedure   
+                  of degradation.                                    
+        [-full] : flag for full steps grid, instead of default partial
+                  steps.
+       
+      REQUIRED FILES :
+        Files mesh_hgr.nc, mesh_zgr.nc, mask.nc
+       
+      OUTPUT : 
+        netcdf file : degraded_cdfvar.nc 
+        netcdf file : flsdc.nc
+       </code></pre>
+
+<h2 id="cdfdegradu">cdfdegradu</h2>
+
+<pre><code>  usage : cdfdegradu IN-Ufile IN-var ri rj [i0 j0]
+        ... [-full]
+        
+      PURPOSE :
+        Degrad the horizontal resolution of NEMO U-grid ouput,       
+        for each z-level and time step, with a ratio of ri along     
+        x direction and rj along y direction. If specified, the input
+        grid is considered starting from the indices i0 and j0.      
+       
+      ARGUMENTS :
+        IN-Ufile  : netcdf U-file.
+        IN-var    : name of netcdf variable to work with
+        ri        : degradation ratio for x-direction   
+        rj        : degradation ratio for y-direction   
+       
+      OPTIONS : 
+        [i0 j0] : spatial indices from where starting the procedure   
+                  of degradation.                                    
+        [-full] : flag for full steps grid, instead of default partial
+                  steps.
+       
+      REQUIRED FILES :
+        Files mesh_hgr.nc, mesh_zgr.nc, mask.nc
+       
+      OUTPUT : 
+        netcdf file : degraded_cdfvar.nc 
+        netcdf file : flsdc.nc
+       </code></pre>
+
+<h2 id="cdfdegradv">cdfdegradv</h2>
+
+<pre><code>  usage : cdfdegradv IN-Vfile IN-var ri rj [i0 j0]
+        ... [-full]
+        
+      PURPOSE :
+        Degrad the horizontal resolution of NEMO V-grid ouput,       
+        for each z-level and time step, with a ratio of ri along     
+        x direction and rj along y direction. If specified, the input
+        grid is considered starting from the indices i0 and j0.      
+       
+      ARGUMENTS :
+        IN-Vfile  : netcdf V-file.
+        IN-var    : name of netcdf variable to work with
+        ri        : degradation ratio for x-direction   
+        rj        : degradation ratio for y-direction   
+       
+      OPTIONS : 
+        [i0 j0] : spatial indices from where starting the procedure   
+                  of degradation.                                    
+        [-full] : flag for full steps grid, instead of default partial
+                  steps.
+       
+      REQUIRED FILES :
+        Files mesh_hgr.nc, mesh_zgr.nc, mask.nc
+       
+      OUTPUT : 
+        netcdf file : degraded_cdfvar.nc 
+        netcdf file : flsdc.nc
+       </code></pre>
+
+<h2 id="cdfdegradw">cdfdegradw</h2>
+
+<pre><code>  usage : cdfdegradw IN-Wfile IN-var ri rj [i0 j0]
+        ... [-full]
+        
+      PURPOSE :
+        Degrad the horizontal resolution of NEMO W-grid ouput,       
+        for each z-level and time step, with a ratio of ri along     
+        x direction and rj along y direction. If specified, the input
+        grid is considered starting from the indices i0 and j0.      
+       
+      ARGUMENTS :
+        IN-Wfile  : netcdf W-file.
+        IN-var    : name of netcdf variable to work with
+        ri        : degradation ratio for x-direction   
+        rj        : degradation ratio for y-direction   
+       
+      OPTIONS : 
+        [i0 j0] : spatial indices from where starting the procedure   
+                  of degradation.                                    
+        [-full] : flag for full steps grid, instead of default partial
+                  steps.
+       
+      REQUIRED FILES :
+        Files mesh_hgr.nc, mesh_zgr.nc, mask.nc
+       
+      OUTPUT : 
+        netcdf file : degraded_cdfvar.nc 
+        netcdf file : flsdc.nc
+       </code></pre>
+
+<h2 id="cdfdifmask">cdfdifmask</h2>
+
+<pre><code>  usage : cdfdifmask  mask1 mask2
+      PURPOSE :
+        Compute the difference between 2 mask files.
+       
+      ARGUMENTS :
+        mask1, mask2 : model files to be compared.
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        netcdf file : mask_diff.nc
+        variables : tmask, umask, vmask, fmask</code></pre>
+
+<h2 id="cdfdiv">cdfdiv</h2>
+
+<pre><code>  usage : cdfdiv -u U-file U-var -v V-file V-var -l levlist  [-8]...
+            ... [-surf] [-overf] [-full] [-o OUT-file ]
+       
+      PURPOSE :
+        Compute the divergence of the flow from the U and V velocity components
+       
+      ARGUMENTS :
+        -u U-file U-var : file and variable name for zonal component
+        -v V-file V-var : file and variable name for meridional component
+        -l levlist    : levels to be processed. If set to 0, assume forcing file
+                 in input. Example of recognized syntax :
+                   -l "1,10,30"  or -l "1-20" or even -l "1-3,10-20,30-"
+                   -l  1 . Note that -l "3-" set a levlist from 3 to the bottom
+ 
+      OPTIONS :
+        -8 : save in double precision instead of standard simple precision.
+        -surf : work with single level C-grid (not forcing)
+        -overf : store the ratio curl/f where f is the coriolis parameter
+        [ -full ] : in case of full step configuration. Default is partial step.
+        -o OUT-file : specify output file name instead of curl.nc
+       
+      REQUIRED FILES :
+         mesh_hgr.nc mesh_zgr.nc
+       
+      OUTPUT : 
+        netcdf file : curl.nc
+          variables : div units : s^-1
+                or divoverf, no units (if -overf option)</code></pre>
+
+<h2 id="cdfeddyscale">cdfeddyscale</h2>
+
+<pre><code>  usage : cdfeddyscale mean-cdfeddyscale_pass1-file
+       
+      PURPOSE :
+      Compute: -the Taylor scale or large scale eddy (lambda1)
+               -the small scale eddy (lambda2)
+               -and the inertial range (scar) on F-points
+       
+      lambda1 = sqrt(mean Kinetic Energie / Enstrophy)
+      lambda2 = sqrt(Enstrophy / Palinstrophy)
+      Inertial Range    = lambda1 / lambda2
+       
+      Enstrophy = 1/2 * ( mean((RV)^2) )
+      Palinstrophy = 1/2 * ( mean((dx(RV))^2 + (dy(RV))^2) )
+       
+      ARGUMENTS :
+      mean-cdfeddyscale_pass1-file : mean of the terms compute by
+      the program cdfeddyscale_pass1
+       
+      OUTPUT : 
+        netcdf file : lambda.nc
+          variables : solambda1 (m), solambda2 (m), soscar
+       
+      SEE ALSO :
+        cdfeddyscale_pass1 </code></pre>
+
+<h2 id="cdfeddyscale_pass1">cdfeddyscale_pass1</h2>
+
+<pre><code>  usage : cdfeddyscale_pass1 U-file V-file U-var V-var lev
+       
+      PURPOSE :
+      Compute: - the curl and the square of curl on F-points,
+               - the gradient components of the curl and the
+                 square of the gradient components on UV-points,
+               - the square of velocity components on UV-points,
+      for given gridU gridV files and variables. These variables are required
+      for computing eddy scales with cdfeddyscale. Therefore this program is
+      the first step in computing the eddy scales.
+      
+         These terms will used to compute the Taylor scale or large
+      scale eddy (lambda1) and the small scale eddy (lambda2) in
+      the program cdfeddyscale.
+       
+      ARGUMENTS :
+        U-file : zonal component of the vector field.
+        V-file : meridional component of the vector field.
+        U-var  : zonal component variable name
+        V-var  : meridional component variable name.
+        lev    : level to be processed. If set to 0, assume forcing file 
+                 in input.
+       
+      REQUIRED FILES :
+         mesh_hgr.nc
+       
+      OUTPUT : 
+        netcdf file : lambda_int.nc
+          variables : socurl (s^-1), socurl2 (s^-2)
+          variables : sodxcurl, sodycurl (s^-1.m^-1)
+          variables : sodxcurl2, sodycurl2 (s^-2.m^-2)
+          variables : vozocrtx2, vomecrty2 (m^2.s^-2)
+          WARNING : variables in the output file are not located at the same
+                  C-grid point.
+       
+      SEE ALSO : 
+         cdfeddyscale</code></pre>
+
+<h2 id="cdfeke">cdfeke</h2>
+
+<pre><code>  usage : cdfeke U-file [U2-file]  V-file [V2-file] T-file [-mke ] [-nc4] ...
+             ... [-o output_file]
+       
+      PURPOSE :
+         Compute the Eddy Kinetic Energy from previously computed
+         mean values and mean squared values of velocity components.
+       
+      ARGUMENTS : both 'General Use' or 'Reduced Use' are acceptable
+       * General Use: 5 files are given in argument, and EKE is computed
+        U-file  : gridU type file with mean U component.
+        U2-file : gridU2 type file with mean U2 component.
+        V-file  : gridV type file with mean V component.
+        V2-file : gridV2 type file with mean V2 component.
+        T-file  : any gridT or gridT2 (smaller) file, used for EKE header.
+        
+       * Reduced Use: no U2/V2 file, only MKE is computed from U and V file.
+        U-file  : gridU type file with mean U component.
+        V-file  : gridV type file with mean V component.
+        T-file  : any gridT or gridT2 (smaller) file, used for MKE header.
+              
+      OPTION :
+        -mke  : output MKE field together with EKE. 
+        -nc4  : allow netcdf4 output with compression and chunking.
+        -o output file : specify output file name instead of eke.nc
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        netcdf file : eke.nc unless -o option in use.
+          variables : voeke (m2/s)
+          variables : vomke (m2/s) if required</code></pre>
+
+<h2 id="cdfenstat">cdfenstat</h2>
+
+<pre><code>  usage : cdfenstat list_of_model_files [-spval0] [-nc4] [-v4d] -o OUT-file]
+      PURPOSE :
+        Compute the time average of a list of files given as arguments.
+        This program handle multi time-frame files is such a way that
+        the output files are also multi time-frame, each frame being
+        the average across the files given in the list.
+        
+        The program assume that all files in the list are of same
+        type (shape, variables , and number of time frames ). 
+        For some variables, the program also compute the time average 
+        of the squared variables, which is used in other cdftools 
+        (cdfeke, cdfrmsssh, cdfstdevw, cdfstddevts ... The actual variables
+        selected for squared average are :
+          - vozocrtx
+          - vomecrty
+          - vovecrtz
+          - sossheig
+        This selection can be adapted with the nam_cdf_namelist process.
+        (See cdfnamelist -i for details).
+        If you want to compute the average of already averaged files,
+        consider using cdfmoy_weighted instead, in order to take into
+        account a particular weight for each file in the list.
+       
+      ARGUMENTS :
+        A list of similar model output files. 
+       
+      OPTIONS :
+        [ -spval0 ] :  set missing_value attribute to 0 for all output
+                variables and take care of the input missing_value.
+                This option is usefull if missing_values differ from files 
+                to files; it was formely done by cdfmoy_chsp).
+        [ -nc4 ] : output file will be in netcdf4, with chunking and deflation
+        [ -v4d ] : uses 4D arrays for improved performance (use more memory !)
+        [ -o OUT-file ] : specify a name for output file instead of cdfmoy.nc
+       
+      REQUIRED FILES :
+        none 
+       
+      OUTPUT : 
+        netcdf file : cdfmoy.ncunless -o option in use
+        variables : are the same than in the input files. Standard Dev are 
+         named  stdev_<variable></code></pre>
+
+<h2 id="cdfets">cdfets</h2>
+
+<pre><code>  usage : cdfets  T-file 
+       
+      PURPOSE :
+        Compute the eddy time scale, and a proxy for rossby radius.
+        The Rossby radius is computed as the vertical integral of N2
+        (Brunt Vaissala frequency), scaled by |f|*pi
+        The Eddy Time Scale is the ratio N/|grad B| where N is the square
+        root of N2 and |grad B| is the module of the horizontal buoyancy
+        gradient. B is the buoyancy computed as B=-g rho/rho0.
+       
+      ARGUMENTS :
+        T-file : netcdf input file for temperature and salinity (gridT).
+       
+      REQUIRED FILES :
+         mesh_hgr.nc, mesh_zgr.nc
+       
+      OUTPUT : 
+        netcdf file : ets.nc
+          variables : voets (days)  and sorosrad (m)</code></pre>
+
+<h2 id="cdffindij">cdffindij</h2>
+
+<pre><code>  usage :   cdffindij  xmin xmax ymin ymax  [-c COOR-file] [-p point_type]...
+                     [-f list_file ] [-d decriptor] [-o output_file] [-a] [-l]
+       
+      PURPOSE :
+        Return the model limit (i,j space) of the geographical window 
+        given on the input line. If using -f list_file option, then the output
+        is just a single point, not a window, and xmin, xmax, ymin ymax are not
+        used at all.
+       
+      ARGUMENTS :
+        xmin xmax ymin ymax : geographical limits of the window, in lon/lat
+        (relevant only if -f option not used.)
+       
+      OPTIONS :
+        [-c COOR-file ] : specify a particular coordinate file
+                      default is coordinates.nc
+        [-p point type] : specify the point on the C-grid (T U V F)
+                      default is F
+        [-f list_file ] : list_file is an ascii file describing the location
+                 (one per line) of geographical points to be translated to 
+                 model (i,j) point. Unless specified with -d option, this list
+                 file contains Longitude (X) Latitudes (Y) information.
+        [-d descriptor] : descriptor is a string indicating the position of
+                 X and Y coordinates for the lines of list_file. Default value
+                 of the descriptor is 'XY'. Any other field on the line is 
+                 indicated with any characterm except X or Y. Example of valid
+                 descriptor : 'oXYooo' or 'ooYabcdfXooo' 
+        [-a  ] : With this option, output is similar to input with I,J appended
+                 to the corresponding line.
+        [-l  ] : With this option, also output the exact model longitude and 
+                 latitude of the I,J point.
+        [-o output_file] : write output in ascii output_file instead of standard
+                 output.
+       
+      REQUIRED FILES :
+        coordinates.nc or the specified coordinates file.
+       
+      OUTPUT : 
+        Output is done on standard output.</code></pre>
+
+<h2 id="cdffixtime">cdffixtime</h2>
+
+<pre><code>  usage : cdffixtime  -f IN-file -i initial date [-t tag] [-dt freq] ... 
+                ...  [-keep ] [-leap] [ -noleap]
+       
+      PURPOSE :
+         Change time_counter in file to set it according to drakkar rule,
+         time_counter attibutes 'units' and 'time_origin' are ajusted.
+          * units are 'seconds since yyyy-mm-dd hh:mm:ss' 
+          * time_origin is set to 'yyyy-MMM-dd hh:mm:ss', MMM represents a
+         litteral abbreviation for the month (eg: JAN FEB MAR ...)
+         Once fixed, the time_counter indicates the middle of the output 
+         interval (in case of averaged output, of course).
+       
+      ARGUMENTS :
+        -f IN-file     : specify the file whose time_counter need adjustment
+        -i inital date : indicate the time origin in a fixed 2 words format
+                    yyyy-mm-dd hh:mm:ss ( eg: 1956-05-16 04:30:00 )
+       
+      OPTIONS :
+        [ -t tag ]  : supply a time tag corresponding to the file. If not
+                      supplied, tag is taken from the name of the input file
+                      assuming DRAKKAR convention ( CONFIG-CASE_tag_xxxx.nc )
+        [ -dt freq] : number of days between model output [ 5d ]
+        [-leap ]    : assume a calendar with leap years
+        [-noleap ]  : assume a calendar without leap years (default)
+        [-keep ]    : keep the actual value of time_counter, adjust time_counter
+                     attributes only;
+       
+      REQUIRED FILES :
+        none 
+       
+      OUTPUT : 
+        netcdf file : Input file is modified (only attributes)
+       </code></pre>
+
+<h2 id="cdfflxconv">cdfflxconv</h2>
+
+<pre><code>  Usage : cdfflxconv YEAR config 
+     Output 6 cdf files : for emp, qnet, qsr, sst, taux, tauy with standard var 
+ name :
+         sowaflup, sohefldo, soshfldo, sst, sozotaux, sometauy 
+     coordinates.diags ( clipper like) is required in current dir </code></pre>
+
+<h2 id="cdffracinv">cdffracinv</h2>
+
+<pre><code>  usage : cdffracinv TRC-file [-inv INV-name]
+       
+      PURPOSE :
+        Compute the fraction of inventory for passive tracers, which is 
+        the ratio between inventory at a grid point and the total inventory.
+       
+      ARGUMENTS :
+        TRC-file : netcdf file with tracer inventory.
+       
+      OPTIONS :
+        -inv INV-name  : name of the netcdf name for inventory [ invcfc ]
+       
+      REQUIRED FILES :
+        none ... but : horizontal weight to be coded ?
+       
+      OUTPUT : 
+        netcdf file : fracinv.nc
+          variables : fracinv</code></pre>
+
+<h2 id="cdffwc">cdffwc</h2>
+
+<pre><code>  usage : cdffwc IN-file BASIN-var1,var2,.. [-o OUT-file] [-sref REFSAL]
+                 [-full] [-accum] [-ssh]
+       
+      PURPOSE :
+        Computes the freshwater content in a given basin from top
+        to bottom for each layer. Can handle full step configuration
+        using the -full option.
+       
+      ARGUMENTS :
+         IN-file            : netcdf input file.
+         BASIN-var1,var2,.. : Comma separated list of sub-basin variables
+                              to process.
+         OUT-file           : use specified output file instead of <IN-var>.nc
+       
+      OPTIONS :
+         -full  : for full step computation 
+         -accum : compute accumulated content from top to bottom
+         -ssh   : take ssh into account for surface layer
+         -sref  : reference salinity (= 34.7 by deafult)
+       
+      REQUIRED FILES :
+        mesh_zgr.nc, mesh_hgr.nc and subbasins.nc and mask.nc
+       
+      OUTPUT : 
+        netcdf file :  fwc.nc (or specified with -o option)
+          variables :  fwc_BASIN, where BASIN was set by argument BASIN-var*
+                       (cAsE sensitive !)
+       </code></pre>
+
+<h2 id="cdfgeo-uv">cdfgeo-uv</h2>
+
+<pre><code>  usage : cdfgeo-uv -f T-file [-o UOUT-file VOUT-file ] [ -C option ]
+       
+      PURPOSE :
+          Compute the geostrophic velocity component from the gradient 
+        of the SSH read in the input file. 
+          Without any -C option, the zonal component is located on a 
+        C-grid V point, the meridional one is located on C-Grid U point.
+          See the use of the -C option in order to have (Ugeo, Vgeo) 
+        at (U,V) points on the C-grid.
+       
+      ARGUMENTS :
+       -f  T-file : netcdf file with SSH (input).
+       
+      OPTIONS :
+       -o UOUT-file VOUT-file: specify the names of the output files.
+                 Default are: ugeo.nc vgeo.nc.
+       -C option : Using this option, the output velocity component are
+                at the correct (U,V) points on the C-grid
+                2 options are available :
+               option = 1 : SSH is interpolated on the F point prior derivation
+               option = 2 : Ugeo and Vgeo are interpolated on the C-grid after
+                      derivation
+                  Both option should give very similar results...
+   
+      REQUIRED FILES :
+         mesh_hgr.nc and mesh_zgr.nc
+       
+      OUTPUT : 
+        - netcdf file : ugeo.nc (default)
+            variables : vozocrtx
+            Unless -C option is used : 
+              *** CAUTION:  this variable is located on V-point ***
+        - netcdf file : vgeo.nc (default)
+            variables : vomecrty
+            Unless -C option is used : 
+              *** CAUTION:  this variable is located on U-point ***</code></pre>
+
+<h2 id="cdfgeostrophy">cdfgeostrophy</h2>
+
+<pre><code>  usage : cdfgeostrophy T-file
+       
+      PURPOSE :
+        Compute the geostrophic velocity component from the pressure gradient 
+        computed from SSH and in-situ density (T,S of input file) 
+       
+      WARNING : USE AT YOUR OWN RISKS
+       
+      ARGUMENTS :
+        T-file : netcdf file with SSH, T and S.
+       
+      REQUIRED FILES :
+         mask.nc mesh_hgr.nc and mesh_zgr.nc
+       
+      OUTPUT : 
+        - netcdf file : ugeo.nc
+            variables : vozocrtx
+        - netcdf file : vgeo.nc
+            variables : vomecrty</code></pre>
+
+<h2 id="cdfgradT">cdfgradT</h2>
+
+<pre><code>  usage : cdfgradT T-file [S-file] 
+       
+      PURPOSE :
+         Compute horizontal and vertical gradient of temperature and salinity.
+       Results are saved at U point for zonal gradient, V point for meridional
+       gradient and W for vertical gradient.
+       
+      ARGUMENTS :
+        T-file : File with votemper and vosaline variables
+            If vosaline not in T-file give a second name for S-file.
+       
+      OPTIONS :
+        S-file : File with vosaline variable if not in T file
+       
+      REQUIRED FILES :
+        mesh_hgr.nc mask.nc and mesh_zgr.nc
+       
+      OUTPUT : 
+        netcdf file : gradT.nc
+                     6  variables : 
+               vozogradt, vomegradt, vovegradt : 3 component of the temperature
+                           located respectively at U, V and W points
+               vozograds, vomegrads, vovegrads : 3 component of the salinity
+                           located respectively at U, V and W points
+       
+      SEE ALSO :
+       
+       </code></pre>
+
+<h2 id="cdfhdy">cdfhdy</h2>
+
+<pre><code>  usage : cdfhdy T-file level1 level2
+       
+      PURPOSE :
+         Compute dynamical height anomaly field from gridT file.
+         It is computed as the integral of (1/g) *10e4 * sum [ delta * dz ]
+             where delta = (1/rho - 1/rho0)
+             10e4 factor is for the conversion decibar to pascal.
+       
+      ARGUMENTS :
+         T-file  : netcdf file with temperature and salinity
+         level1  : upper limit for vertical integration (usually 1 = surface)
+         level2  : lower limit for vertical integration.
+       
+      REQUIRED FILES :
+        mask.nc and mesh_zgr.nc
+       
+      OUTPUT : 
+        netcdf file : cdfhdy.nc
+          variables : sohdy (m)</code></pre>
+
+<h2 id="cdfhdy3d">cdfhdy3d</h2>
+
+<pre><code>  usage : cdfhdy3d T-file
+       
+      PURPOSE :
+         Compute dynamic height anomaly from T-file given as argument.
+       
+      ARGUMENTS :
+        T-file : netcdf file with temperature and salinity.
+       
+       
+      REQUIRED FILES :
+         mask.nc and mesh_zgr.nc
+       
+      OUTPUT : 
+        netcdf file : cdfhdy3d.nc
+          variables : vohdy ( m )
+       
+      SEE ALSO :
+       cdfhdy
+       </code></pre>
+
+<h2 id="cdfheatc">cdfheatc</h2>
+
+<pre><code>  usage :  cdfheatc  -f T-file [-mxloption option] ...
+      [-zoom imin imax jmin jmax kmin kmax] [-full] [-o OUT-file]
+      [-M MSK-file VAR-mask ]
+       
+      PURPOSE :
+         Computes the heat content in the specified 3D area (Joules)
+       
+      ARGUMENTS :
+        -f T-file : name of the input file with temperature (and MLD if needed).
+       
+      OPTIONS :
+        [-zoom imin imax jmin jmax kmin kmax] : limit of a sub domain where
+                       the heat content will be calculated.
+                    - if imin = 0 then ALL i are taken
+                    - if jmin = 0 then ALL j are taken
+                    - if kmin = 0 then ALL k are taken
+        [-full ] : assume full step model output instead of default
+                   partial steps.
+        [-mxloption option]: option= 1 : compute only in the mixed layer,
+                             option=-1 : exclude mixed layer in the computation
+                             option= 0 : [Default], do not take care of mxl.
+        [-o OUT-file ] : specify netcdf output filename instead of heatc.nc
+        [-M MSK-file VAR-mask] : Allow the use of a non standard mask file 
+               with VAR-mask, instead of mask.nc and tmask
+               This option is a usefull alternative to -zoom option, when the 
+               area of interest is not 'box-like' 
+       
+      REQUIRED FILES :
+        Files mesh_hgr.nc, mesh_zgr.nc and mask.nc
+       
+      OUTPUT : 
+        netcdf file : heatc.nc unless -o option is used.
+               variables: heatc3d (Joules)
+                        : heatc(dep) (Joules) 
+                        : heatc3dpervol (Joules/m3) 
+        Standard output
+        
+       SEE ALSO: 
+           cdfpolymask </code></pre>
+
+<h2 id="cdfhflx">cdfhflx</h2>
+
+<pre><code>  usage : cdfhflx  T-file 
+       
+      PURPOSE :
+        Computes the Meridional Heat Transport (MHT) from surface heat fluxes,
+        in function of the latitude.
+        If a sub-basin file is available, MHT is computed for each sub-basin.
+        Note that the latitude is in fact a line of constant J coordinate, not
+        a true parallel, if the model grid is distorted as in the northern most
+        part of ORCA configurations.
+       
+      ARGUMENTS :
+        T-file : a file with heat fluxes (gridT). 
+       
+      REQUIRED FILES :
+        Files mesh_hgr.nc, new_maskglo.nc and mask.nc.
+        If new_maskglo.nc is not available, only global MHT is computed.
+       
+      OUTPUT : 
+        ASCII file  : hflx.out
+        netcdf file : cdfhflx.nc
+          variables : hflx_glo, [hflx_atl, hflx_inp, hflx_pac, hflx_ind]</code></pre>
+
+<h2 id="cdfhgradb">cdfhgradb</h2>
+
+<pre><code>  usage : cdfhgradb -t T-file [-s S-file] [-nc4 ] [-o OUT-file] ...
+                    ...  [-sal SAL-name]  [-tem TEMP-name] 
+       
+      PURPOSE :
+         Compute the norm of the horizontal buoyancy gradient.
+       Results are saved at T points.
+       
+      ARGUMENTS :
+        -t T-file : File with votemper and vosaline variables
+            If vosaline not in T-file use -s option.
+           Note that salinity and/or temperature variables name can be changed
+           with -sal and/or -tem options, respectively.
+       
+      OPTIONS :
+       [-s S-file ] : File with vosaline variable if not in T file
+       [-nc4      ] : use netcdf4 chunking and deflation on output 
+       [-o output file] : specify the name of output file instead of 
+                 default name hgradb_gridT.nc
+       [-sal SAL-name] : specify the name of salinity variable
+       [-tem TEM-name] : specify the name of temperature variable
+       
+      REQUIRED FILES :
+        mesh_hgr.nc mask.nc and mesh_zgr.nc
+       
+      OUTPUT : 
+        netcdf file : hgradb_gridT.nc ( unless specified with -o option)
+                     1  variables : 
+               vohgradb: norm of the horizontal buoyancy gradient at t-point
+       
+      SEE ALSO :
+         cdfbuoyflx  
+       </code></pre>
+
+<h2 id="cdficb_clim">cdficb_clim</h2>
+
+<pre><code>  usage : cdficb_clim 12-ICB-monthly-means-files
+       
+      PURPOSE :
+         Compute the 2D field of icb mass and icb melt.
+       
+      ARGUMENTS :
+        ICE-file : netcdf icb file
+       
+      REQUIRED FILES :
+         mesh_hgr.nc and mask.nc
+       
+      OUTPUT : 
+        netcdf file : icbdiags.nc
+          variables : Mass  (Kg/m2 )
+                      Melt  (Kg/m2/s )</code></pre>
+
+<h2 id="cdficb_diags">cdficb_diags</h2>
+
+<pre><code>  usage : cdficb_diags ICB-file  
+       
+      PURPOSE :
+         Compute the spatially integrated icb mass and melt flux.
+       
+      ARGUMENTS :
+        ICB-file : a single netcdf icb file
+       
+      REQUIRED FILES :
+         mesh_hgr.nc and mask.nc
+       
+      OUTPUT : 
+        netcdf file : icbdiags.nc
+          variables : [NS]Mass  (Kg )
+                      [NS]Melt    (Kg/s )
+                N = northern hemisphere
+                S = southern hemisphere
+        standard output</code></pre>
+
+<h2 id="cdficediags">cdficediags</h2>
+
+<pre><code>  usage : cdficediag ICE-file [-lim3] 
+       
+      PURPOSE :
+         Compute the ice volume, area and extent for each hemisphere.
+         The extent is computed in a similar way to NSIDC for easy 
+         comparison : the extent is the surface of the grid cells covered
+         by ice when the ice concentration is above 0.15
+       
+         For compatibility with previous version, another estimate of 
+         the extend is computed using grid cell surfaces weighted by the
+         ice concentration, but it will be deprecated soon.
+       
+      ARGUMENTS :
+        ICE-file : netcdf icemod file (LIM2 by default)
+       
+      OPTION :
+        [-lim3 ] : LIM3 variable name convention is used
+        [-o OUT-file ] : specify output file instead of icediags.nc
+       
+      REQUIRED FILES :
+         mesh_hgr.nc and mask.nc
+       
+      OUTPUT : 
+        netcdf file : icediags.nc
+          variables : [NS]Volume  (10^9 m3 )
+                      [NS]Area    (10^9 m2 )
+                      [NS]Extent  (10^9 m2 ) -- obsolete --
+                      [NS]Exnsidc (10^9 m2 )
+                N = northern hemisphere
+                S = southern hemisphere
+        standard output</code></pre>
+
+<h2 id="cdfimprovechk">cdfimprovechk</h2>
+
+<pre><code>  usage : cdfimprovechk IN-var OBS-file REF-file TST-file
+       
+      PURPOSE :
+         Estimate the improvement/deterioration of a test run,
+         compared with a reference run relative to some observations
+         This program computes the quantity zchk= ( REF - TEST )/(REF - OBS)
+         Where 0 < zchk <= 1, the TST is better than the reference
+         Where 1 < zchk, the TST  was corrected in the right sense but too much
+         Where  zchk < 0, the TST  was corrected was corrected in the wrong way.
+       
+      ARGUMENTS :
+         IN-var    : netcdf input variable
+         OBS-file  : netcdf observation file
+         REF-file  : netcdf reference file
+         TST-file  : netcdf test file
+       
+      REQUIRED FILES :
+        none
+       
+      OUTPUT : 
+        netcdf file : chk.nc
+          variables : same as input variable.</code></pre>
+
+<h2 id="cdfinfo">cdfinfo</h2>
+
+<pre><code>  usage : cdfinfo 'model cdf file' [-dep dep] 
+       
+      PURPOSE :
+         Gives very basic information about the file given in arguments.
+       
+      ARGUMENTS :
+         model output file in netcdf.
+       
+      OPTIONS :
+         [-dep depth ] : return the nearest k index corresponding to depth 
+       
+      OUTPUT : 
+         On standard ouput, gives the size of the domain, the depth 
+         dimension name, the number of variables.
+       </code></pre>
+
+<h2 id="cdfisf_fill">cdfisf_fill</h2>
+
+<pre><code>  usage : cdfisf_fill  -f ISF-file -v ISF-var -l ISF-list [-nc4 ] [-o OUT-file]
+       
+      PURPOSE : Build a nc file with a single value for each pool around a list
+                of given point. A warning is given when neighbouring ice-shelves
+                cannot be discriminated (no gap in between). In this case, hand
+                edit on the ISF-file is required.
+       
+      ARGUMENTS : 
+          -f ISF-file : netcdf file  which contains the ice shelf draft variable
+                      (mesh_zgr is OK). It is used as a mask, only.
+          -v ISF-var  : variable name corresponding to the ice shelf draft or 
+                       ice shelf level
+          -l ISF-list : text file containing at least the following information:
+  
+                  1  NAME    LON  LAT I  J 
+                  ...             
+                  i  NAMEi   LON  LAT I  J 
+                  ...             
+                  EOF             
+                  No NAME  X    Y   I  J 
+       
+      OPTIONS : 
+           -nc4 : use NetCDF4 chunking and deflation for the output
+           -o OUT-file : specify the name of the output file instead of fill.nc
+                  This file will be one of the input file for cdfmkforcingisf 
+                  as the ISF-fill_file 
+       
+      OUTPUT : 
+               netcdf file : fill.nc 
+               variable : sofillvar contains for all points in ice shelf NAME 
+                          the value -i (negative value)
+               text file : <ISF-list>_zmin_zmax.txt 
+                         this output file is similar to <ISF-list> but updated
+                         with the minimum and maximul value of ice-draft for 
+                         each shelf.
+       
+      SEE ALSO : 
+            cdfisf_forcing,  cdfisf_rnf 
+       </code></pre>
+
+<h2 id="cdfisf_forcing">cdfisf_forcing</h2>
+
+<pre><code>  usage : cdfisf_forcing -f ISF-fill_file  -v ISF-fill_var -l ISF-listfile 
+              -m ISF-poolmask [-vm ISF-poolmask_variable] [-p PATTERN-file] 
+             [-vp PATTERN-variable] [-nc4] [-o OUT-file ]
+       
+      PURPOSE : 
+          Build basal melting rate file used in NEMO ISF when nn_isf=4 
+       
+      ARGUMENTS : 
+           -f ISF-fill_file : file built by cdfisf_fill (all the ice shelves 
+                              are tagged with an id)
+           -v ISF-fill_var  : name of fill variable to use in ISF-fill_file
+           -l ISF-listfile : text file used to build the ISF-fill_file. 
+                             Only the last variable on each line is used (GT/y)
+       
+      OPTIONS :
+           -p PATTERN-file : specify the file use for patterns. 
+                             [ default : isfpattern.nc ]
+           -vp PATTERN-variable : specify the name of the pattern variable. 
+                             [ default : sowflisf ]
+           -vm ISF-poolmask_variable : specify the name of the variable used 
+                  for masking the pools. [ default : isfpoolmask ]
+           -nc4 : use netcdf4 chunking and deflation
+           -o OUT-file : specify output filename. [ default : isfforcing.nc ]
+               
+      REQUIRED FILES : 
+            mesh_zgr.nc mesh_hgr.nc,
+            isfpattern.nc (ie reference file used to define the isf melting 
+                  pattern), unless -p option is used to give different name.
+       
+      OUTPUT :
+          netcdf file : isfforcing.nc unless specified with -o option
+          variable : sofwfisf 
+       
+      SEE ALSO : cdfisf_fill, cdfisf_rnf, cdfisf_poolchk
+       </code></pre>
+
+<h2 id="cdfisf_poolchk">cdfisf_poolchk</h2>
+
+<pre><code>  usage : cdfisf_poolchk -m MASK-file -d ISFDRAFT-file [-v ISFDRAFT-variable]
+             [-nc4] [-o OUT-file]
+       
+      PURPOSE :
+        Produce a netcdf mask file with 1 everywhere, except for points 
+        not connected to the open ocean (Frequent for cavities below 
+        ice-shelves), which have 0 value. Both 3D and 2D variables are
+        created, the 2D variables beiing used for cdfisf_forcing.
+       
+      ARGUMENTS :
+        -m MASK-file : name of the input NEMO mask file, with tmask variable.
+        -d ISFDRAFT-file : name of the file with ice shelf draft.
+       
+      OPTIONS :
+        -v ISFDRAFT-variable: name of the variable for ice shelf draft.
+        -nc4 : use netcdf4 with chunking and deflation for the output.
+        -o OUT-file : name of the output file. [Default : poolmask.nc ]
+       
+      REQUIRED FILES :
+        Only the mask file given as argument
+       
+      OUTPUT : 
+        netcdf file : poolmask.nc unless -o option is used.
+          variables : tmask_pool3d, tmask_pool2d
+       
+      SEE ALSO :
+       cdfisf_fill, cdfisf_forcing, cdfisf_rnf
+       </code></pre>
+
+<h2 id="cdfisf_rnf">cdfisf_rnf</h2>
+
+<pre><code>  usage : cdfisf_rnf -f ISF-fill-file -v ISF-fill_var -l ISF-listfile -w width 
+      [-b BATHY-file] [-vb BATHY-var] [-i ISFDRAFT-file] [-vi ISFDRAFT-variable]
+      [-nc4] [-o OUT-file ]
+       
+      PURPOSE :
+         Build a netcdf file runoff file using the basal melting of the 
+         ice-shelves. This netcdf file is intented to be used with NEMO when
+         nn_isf namelist parameter is set to 3.
+       
+      ARGUMENTS :
+           -f ISF-fill_file : file built by cdffill (all the ice shelves are
+                              tagged with an id)
+           -v ISF-fill_var  : name of fill variable to use in ISF-fill_file
+           -l ISF-list : Text file with the melting rate (GT/y) given for
+                each ice shelf.
+           -w width : specify the width (in grid points) on which the run-off
+                will be applied.
+       
+      OPTIONS :
+           -b BATHY-file : give name of bathy file.
+                       [ default : bathy.nc ]
+           -vp BATHY-var : give name of bathy variable.
+                       [ default : Bathymetry ]
+           -i ISFDRAFT-file : give name of isf_draft file.
+                       [ default : isf_draft.nc ]
+           -vi ISFDRAFT-var : give name of isf_draft variable.
+                       [ default : isf_draft ]
+           -nc4 : Use this option to have netcdf4 output file, with chunking
+                and deflation.
+           -o OUT-file : Specify the name of the output file instead of 
+                the default name rnfisf.nc
+       
+      REQUIRED FILES :
+        mesh_hgr.nc and all files specified on the command line
+       
+      OUTPUT : 
+        netcdf file : rnfisf.nc unless -o option used
+          variables : sozisfmax (m), sozisfmin(m), sofwfisf (kg/m2/s)
+       
+      SEE ALSO :
+        cdfisf_fill, cdfisf_forcing, cdfisf_poolchk
+       </code></pre>
+
+<h2 id="cdfisopsi">cdfisopsi</h2>
+
+<pre><code>  usage : cdfisopsi ref_level sigma_ref gridT 
+       Compute  a geostrophic streamfunction
+       projected  on an isopycn.
+          ref_level = reference level for pot. density
+          sigma_ref = density level to project on
+          gridT     = input file for temperature and salinity
+   
+          Output on isopsi.nc variable soisopsi
+          Depths are taken from input file 
+          requires mesh_hgr.nc and mesh_zgr.nc</code></pre>
+
+<h2 id="cdfkempemekeepe">cdfkempemekeepe</h2>
+
+<pre><code> usage : cdfkempemekeepe file
+      Produce a cdf file transfertst1t3.nc with wT and anowT variables
+      file is from cdfmoyuvwt
+      the mean must have been computed on a period long enough
+      for the statistics to be meaningful
+                          </code></pre>
+
+<h2 id="cdflap">cdflap</h2>
+
+<pre><code>  usage : cdflap IN-file IN-var  IN-type [-overf2] [-nometric]
+       
+      PURPOSE :
+        Compute the Laplacian of the variable IN-var in file IN-file
+        Assumes that the data are on a C-grid model (as NEMO) 
+       
+      ARGUMENTS :
+        IN-file : netcdf file in input
+        IN-var  : name of the variable to process 
+        IN-TYPE : Position of the variable on the C-grid [ T U V F ]
+       
+      OPTIONS :
+        -overf2 : save laplacien/f/f*g (where f is the local coriolis 
+             parameter, and g is the accelaration due to gravity --9.81 m/s2-- )
+             For the SSH field, this is a proxy for geostrophic vorticity
+        -nometric : compute laplacian without considering metrics 
+       
+      REQUIRED FILES :
+        mesh_hgr.nc mesh_zgr.nc and mask.nc
+       
+      OUTPUT : 
+        netcdf file : lap.nc
+          variables : lap<var> (unit/m2)
+        if option -overf2 is used, netcdf file is lapoverf2.nc and 
+        variable is lap<var>overf2</code></pre>
+
+<h2 id="cdflinreg">cdflinreg</h2>
+
+<pre><code>  usage : cdflinreg 'list of model files' 
+       
+      PURPOSE :
+         Compute the linear regression coefficients for a bunch of
+         input files. 
+       
+      ARGUMENTS :
+        A list of netcdf model file of same kind
+       
+      REQUIRED FILES :
+        none
+       
+      OUTPUT : 
+        netcdf file : linreg.nc
+          variables : for each input variables, there are 3 computed field
+                 - slope coefficient
+                 - barycenter 
+                 - Pearson Coefficient</code></pre>
+
+<h2 id="cdfmaskdmp">cdfmaskdmp</h2>
+
+<pre><code>  usage : cdfmaskdmp T-file S-file  ... 
+                ... [ref_dep snmin swidth hmin hwidth latmax latwidth]
+       
+      PURPOSE :
+        Compute a damping mask with smooth transition according to density,
+        depth and latitude criteria.
+       
+      ARGUMENTS :
+        T-file : temperature file
+        S-file : salinity file
+         They can be the same file, but as many climatologied are provided
+         in separate files, we decided to put both in the command line.
+       
+      OPTIONS :
+         ** If used, they must all be provided in the correct order (!) **
+        ref_dep  : reference depth for potential density.
+        snmin    : density minimum for the mask.
+        swidth   : density width for tapering
+        hmin     : minimum depth
+        hwidth   : depth width  for tapering
+        latmax   : maximum latitude
+        latwidth : latitude width  for tapering
+       
+        Actual default values are :
+         ref_dep  =    2000.000    
+         snmin    =    37.16000    
+         swidth   =   2.5000000E-02
+         hmin     =    1000.000    
+         hwidth   =    100.0000    
+         latmax   =   -20.00000    
+         latwidth =    2.000000    
+       
+      REQUIRED FILES :
+        mask.nc
+       
+      OUTPUT : 
+        netcdf file : mask_dmp.nc
+          variables : wdmp</code></pre>
+
+<h2 id="cdfmax">cdfmax</h2>
+
+<pre><code>  usage : cdfmax -f file -var cdfvar ...
+       ... [-lev kmin kmax ] [-zoom imin imax jmin jmax] ...
+       ... [-time tmin tmax ] [-fact multfact]  [-xy ]
+       
+      PURPOSE :
+         Find minimum and maximum of a file as well as their 
+         respective location. Options allow to restrict the 
+         finding to a sub area in time and space. This program
+         also deal with vertical slabs in a domain.
+       
+      ARGUMENTS :
+        -f file  : input file 
+        -var cdfvar : input variable
+       
+      OPTIONS :
+        [-lev kmin kmax ] : restrict to level between kmin and kmax. 
+        [-zoom imin imax jmin jmax] : restrict to sub area specified
+                        by the given limits. If the zoomed area is 
+                        degenerated to a single line, then the vertical
+                        slab is considered as domain.
+        [-time tmin tmax ] : restrict to the indicated time windows.
+        [-fact multfact] : use a multiplicative factor for the output
+        [-xy ] : force horizontal slab even in the case of a degenerated
+                        zoomed area.
+       
+      REQUIRED FILES :
+        none
+       
+      OUTPUT : 
+        output is done on standard output.</code></pre>
+
+<h2 id="cdfmaxmoc">cdfmaxmoc</h2>
+
+<pre><code>  usage : cdfmaxmoc OVT-file basin_name latmin latmax depmin depmax
+       
+      PURPOSE :
+         Compute the maximum and minimum of the overturning, from file OVT-file,
+         for oceanic basin specified by cbasin, and in the geographical frame 
+         defined by latmin latmax, depmin, depmax.
+       
+      ARGUMENTS :
+        OVT-file   : overturning file from cdfmoc, with or w/o sub basins.
+        basin_name : name of oceanic subbasin as defined in new_maskglo.nc
+                 usually it can be one of atl, glo, inp, ind or pac
+                 glo means no subbasins.
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        netcdf file : maxmoc.nc
+          6 variables : 
+             maxmoc, minmoc ( sv )      : max and min of overturning
+             latmaxmoc latminmoc ( deg) : latitudes of max and min.
+             depmaxmoc depminmoc ( m)   : depth of max amd min .
+       
+      SEE ALSO :
+        cdfmoc 
+       </code></pre>
+
+<h2 id="cdfmean">cdfmean</h2>
+
+<pre><code>  usage : cdfmean  IN-file IN-var T|U|V|F|W [imin imax jmin jmax kmin kmax]
+        ... [-full] [-var] [-zeromean] [-M MSK-file VAR-mask ]
+        ... [-o OUT-file] [ -ot OUTASCII-file] [-oz ZEROMEAN-file]
+        ... [ -ov VAR-file]
+       
+      PURPOSE :
+         Computes the mean value of the field (3D, weighted). For 3D fields,
+         a horizontal mean for each level is also given. If a spatial window
+         is specified, the mean value is computed only in this window.
+       
+      ARGUMENTS :
+        IN-file : input netcdf file.
+        IN-var  : name of netcdf variable to work with.
+        T|U|V|F|W : position of cdfvar on the C-grid
+       
+      OPTIONS :
+        [imin imax jmin jmax kmin kmax] : spatial windows where mean value 
+                   is computed:
+                   if imin = 0 then ALL i are taken
+                   if jmin = 0 then ALL j are taken
+                   if kmin = 0 then ALL k are taken
+        [-M MSK-file VAR-mask] : Allow the use of a non standard mask file 
+               with VAR-mask, instead of mask.nc and 
+               This option is a usefull alternative to the previous options, whe
+ n the 
+               area of interest is not 'box-like'
+        [ -full ] : compute the mean for full steps, instead of default 
+                    partial steps.
+        [ -var ]  : also compute the spatial variance of cdfvar 
+        [ -zeromean ] : create a file with cdfvar having a zero spatial mean.
+        [ -o OUT-file] : specify the name of the output file instead of 
+ cdfmean.nc
+        [ -ot OUTASCII-file] : specify the name of the output ASCII file instead
+  
+                    of cdfmean.txt
+        [ -oz ZEROMEAN-file] : specify the name of the output file for option 
+                    -zeromean, instead of zeromean.nc
+        [ -ov VAR-file] : specify the name of the output file for option 
+                    -var, instead of cdfvar.txt
+       
+      REQUIRED FILES :
+        Files mesh_hgr.nc, mesh_zgr.nc, mask.nc
+       
+      OUTPUT : 
+        - netcdf file : cdfmean.nc
+            variables : mean_cdfvar, mean_3D_cdfvar 
+                     [var_cdfvar, var_3D_cdfvar, in case of -var]
+        - netcdf file : zeromean.nc [ in case of -zeromean option]
+            variables : cdfvar
+        - ASCII files : cdfmean.txt
+                        [ cdfvar.txt, in case of -var ]
+        - all output on ASCII files are also sent to standard output.</code></pre>
+
+<h2 id="cdfmhst">cdfmhst</h2>
+
+<pre><code>  usage : cdfmhst  VT-file | (V-file T-file [S-file])  [MST] [-full] ...
+               ...  [-Zdim] [-o OUT-file]
+       
+      PURPOSE :
+        Compute the meridional heat/salt transport as a function of 
+        latitude. If the file new_maskglo.nc is provided, the meridional 
+        heat/salt transport for each sub-basin is also computed.
+       
+      ARGUMENTS :
+        VT-file  : netcdf file containing the mean value of the products
+                   U.S, U.T, V.S and V.T (obtained with cdfvT).
+          or   
+        V-file T-file [S-file] : specify V, T S file as separate files. If
+                  S-file is not specified, assume that salinity is in T-file.
+       
+      OPTIONS :
+        [MST ]   : output flag for meridional salt transport on netcdf files.
+                   If not specified, only the MHT is output.
+        [-full ] : to be set for full step case.
+        [-Zdim ] : to be set to output vertical structure of Heat/salt transport
+        [-o OUT-file ] : change name of the output file. Default:mhst.nc
+       
+      REQUIRED FILES :
+         mesh_hgr.nc, mesh_zgr.nc and mask.nc
+         If new_maskglo.nc is also available, sub-basin meridional transports
+         are also computed.
+       
+      OUTPUT : 
+        ASCII files : zonal_heat_trp.dat : Meridional Heat Transport
+                      zonal_salt_trp.dat : Meridional Salt Transport
+        netcdf file : mhst.nc unless -o option is used.
+            variables : ( [... ] : MST option ) 
+                        zomht_glo  : Meridional Heat Transport (global)
+                      [ zomst_glo  : Meridional Salt Transport (global) ] 
+        If new_maskglo.nc is available, per basin meridional transport 
+        are also available:
+                        zomht_atl  : Meridional Heat Transport
+                      [ zomst_atl  : Meridional Salt Transport ]
+                        zomht_inp  : Meridional Heat Transport
+                      [ zomst_inp  : Meridional Salt Transport ]
+                        zomht_ind  : Meridional Heat Transport
+                      [ zomst_ind  : Meridional Salt Transport ]
+                        zomht_pac  : Meridional Heat Transport
+                      [ zomst_pac  : Meridional Salt Transport ]
+                        zomht_inp0 : Meridional Heat Transport
+                      [ zomst_inp0 : Meridional Salt Transport ]</code></pre>
+
+<h2 id="cdfmkmask">cdfmkmask</h2>
+
+<pre><code>  usage : cdfmkmask T-file [-zoom lonmin lonmax latmin latmax] ...
+                    ... [-zoomij iimin iimax ijmin ijmax] ...
+                    ... [-zoombat bathymin bathymax]  ...
+                    ... [-zoomvar varname varmin varmax]  ...
+                    ... [-time ] [-o OUT-file ]
+       
+      PURPOSE :
+        Build a mask file from vosaline array read from the input file.
+        It assumes that land salinity values are set to 0.
+       
+      ARGUMENTS :
+        T-file : netcdf file with salinity.
+                 if T-file = -maskfile, we assume a reference file named mask.nc
+                 with tmask variable.
+                 if T-file = -mbathy, we assume a reference file named 
+                 bathylevel.nc with mbathy variable, giving the number of 
+                 levels in the ocean.
+       
+      OPTIONS :
+        [-zoom lonmin lonmax latmin latmax] : geographical windows used to
+                         limit the area where the mask is builded. Outside
+                         this area, the mask is set to 0.
+        [-zoomij iimin iimax ijmin ijmax] : model grid windows used to
+                         limit the area where the mask is builded. Outside
+                         this area, the mask is set to 0.
+        [-zoombat bathymin bathymax] : depth windows used to
+                         limit the area where the mask is builded. Outside
+                         this area, the mask is set to 0.
+                         Need mesh_zgr.nc
+        [-zoomvar varname varmin varmax] : range of varname used to
+                         limit the area where the mask is builded. Outside
+                         this area, the mask is set to 0.
+        [-time ] : If further time step is available
+                         a mask for each time step is done
+        [-o OUT-file ] : output file name to be used in place of standard
+                         name [ mask_sal.nc ]
+       
+      REQUIRED FILES :
+        If option -zoombat is used, file mesh_zgr.nc is required.
+        If option T-file is -maskfile then mask.nc is required.
+        If option T-file is -mbathy then bathylevel.nc and mesh_zgr.nc
+         are required.
+       
+      OUTPUT : 
+        netcdf file : mask_sal.nc or OUT-file.
+          variables : tmask, umask, vmask, fmask
+                 fmask can differ from standard fmask because it does not
+                 reflect the slip/noslip lateral condition.</code></pre>
+
+<h2 id="cdfmltmask">cdfmltmask</h2>
+
+<pre><code>  usage : cdfmltmask -f IN-file -m MSK-file -v IN-var1,var2,...  
+               -p  T| U | V | F | W | P  [-s _Fillvalue] [-nc4] [-o OUT-file]
+               [ -M MSK-var ]
+       
+      PURPOSE :
+        Multiply IN-var(s) of IN-file by the mask corresponding to the
+        C-grid point position given by the -p argument.
+       
+      ARGUMENTS :
+        -f IN-file  : input netcdf file.
+        -m MSK-file : input netcdf mask file.
+        -v IN-var1,var2,...   : Comma separated list of variable names to mask.
+        -p T| U | V | F | W | P : C-grid position of IN-var
+                 P indicate a polygon mask created by cdfpoly.
+       OPTIONS : 
+         -s _FillValue : specify values for masked areas [0 by default ]
+         -nc4 : output file will be chunked and deflated
+         -o OUT-file : name of output file, instead of <IN-file>_masked
+         -M MSK-var : use MSK-var in the MSK-file, instead of the one defined
+                by default according to the -p option. Overrid -p option.
+       
+      REQUIRED FILES :
+         none, all are given as arguments.
+       
+      OUTPUT : (jvar)
+        The output file is a copy of the input file with only
+        the requested variable masked.
+        netcdf file : IN-file_masked unless specified with -o 
+          variables : IN-var (same as input).</code></pre>
+
+<h2 id="cdfmoc">cdfmoc</h2>
+
+<pre><code>  usage : cdfmoc  V_file [-full] [-decomp ] [T_file] [S_file] [U_file] ...
+                 [-o OUT-file] [-rapid] 
+      PURPOSE :
+        Computes the MOC for oceanic sub basins as described 
+        in new_maskglo.nc
+       
+      ARGUMENTS :
+        V_file : file with meridional velocity component (mandatory).
+        T_file : file with temperature and salinity
+                (required only for -decomp option).
+        S_file  (required only for -rapid option, might be the same as T_file).
+        U_file  (required only for -rapid option).
+       
+      OPTIONS :
+        [-full ] : use full step instead of default partial step
+        [-decomp ] : decompose MOC in 3 components: Geostrophic,
+                  Barotropic,  Ageostrophic). For this option a 
+                  gridT file is required.
+        [-rapid ] : Compute the AMOC at 26.5 N in the same waay than the
+                   RAPID MOCHA array, separating the Gulfstream transport,
+                   and the contribution of different water masses :
+                    - 0-800m      : Thermocline recirculation
+                    - 800-1100m   : AIW recirculation
+                    - 1100-3000m  : upper-NADW recirculation
+                    - 3000-5000m  : lower-NADW recirculation
+                    - 5000-bottom : AABW recirculation
+        [-o OUT-file ] : specify output file instead of moc.nc
+       
+      REQUIRED FILES :
+        Files mesh_hgr.nc mesh_hgr.nc and mask.nc
+        File new_maskglo.nc. If this latter file is not available 
+              only the MOC for the global domain is computed
+       
+      OUTPUT : 
+        netcdf file : moc.nc
+        variables zomsfglo : Global ocean 
+        variables zomsfatl : Atlantic Ocean 
+        variables zomsfinp : Indo Pacific 
+        variables zomsfind : Indian Ocean alone
+        variables zomsfpac : Pacific Ocean alone
+        variables zomsfinp0 : Indo Pacific Net
+       
+        If decomposition is required , ( option -decomp ) add 3 additional
+        variables per basin with suffixes _sh, _bt, _ag.
+       
+        If option -rapid is used the output file (rapid_moc.nc) is degenerated
+        into 6 scalar values : tr_gs, tr_THERM, tr_AIW, tr_UNADW, tr_LNADW, 
+        tr_BW and a vertical profile of the AMOC at 26.5N, as computed
+        traditionally.
+        Additional variables are also computed following CLIVAR-GODAE 
+        reanalysis intercomparison project recommendations. </code></pre>
+
+<h2 id="cdfmocsig">cdfmocsig</h2>
+
+<pre><code>  usage : cdfmocsig  V_file T_file depth_ref [-eiv] [-full]  ... 
+          ...  [-sigmin sigmin] [-sigstp sigstp] [-nbins nbins] [-isodep] [-v]
+      PURPOSE : 
+        Computes the MOC in density-latitude coordinates. The global value
+        is always computed. Values for oceanic sub-basins are calculated
+        if the file new_maskglo.nc is provided.
+        Last arguments is the reference depth for potential density, in m.
+        Actually only 0 1000 or 2000 are available with standard values for
+        density bins. If you specify another reference depth, you must also
+        specify the minimum density, the bin size and the number of bins,
+        with the options -sigmin, -sigstp, -nbins
+       
+      ARGUMENTS :
+         V_file  : Netcdf gridV file
+         T_file  : Netcdf gridT file
+         depth_ref : reference depth for density 
+                for depth values of 0 1000 or 2000, pre-defined limits for
+                minimum density, number of density bins and width of density
+                bins are provided. For other reference depth, you must use
+                -sigmin, -sigstp and -nbins options (see below).
+                Keyword 'ntr' can also be used in place of depth_ref in 
+                order to use neutral density (no default bin defined so far).
+       
+      OPTIONS :
+        [-eiv ] : takes into account VEIV Meridional eddy induced velocity
+                  -> To be used only if Gent and McWilliams parameterization 
+                     has been used 
+        [ -full ] : Works with full step instead of standard partial steps
+        [ -sigmin ] : Specify minimum of density for bining
+        [ -sigstp ] : Specify density step for bining
+        [ -nbins ]  : Specify the number of density bins you want
+        [ -isodep]  : Compute the zonal mean of isopycnal depths used for mocsig
+        [ -v  ]     : Verbose option for more info during execution
+       
+      REQUIRED FILES :
+         Files mesh_zgr.nc, mesh_hgr.nc, mask.nc
+         File new_maskglo.nc is optional [sub basins masks]
+       
+      OUTPUT : 
+        netcdf file : mocsig.nc
+        variables zomsfglo : Global ocean 
+        variables zomsfatl : Atlantic Ocean 
+        variables zomsfinp : Indo Pacific 
+        variables zomsfind : Indian Ocean alone
+        variables zomsfpac : Pacific Ocean alone
+        If file new_maskglo.nc is not present, mask.nc file
+        is used and only zomsfglo is produced.
+        If option -isodep is used, each MOC variable is complemented by a iso
+        variable, giving the zonal mean of ispycnal depth (e.g.zoisoglo).</code></pre>
+
+<h2 id="cdfmoy">cdfmoy</h2>
+
+<pre><code>  usage : cdfmoy list_of_model_files [-spval0] [-cub ] [-zeromean] [-max]
+                [-nomissincl] [-nc4 ] [-o output_file_root ]
+       
+      PURPOSE :
+        Computes the time average of a list of files given as arguments.
+        The program assumes that all files in the list are of same
+        type (shape, variables etc...). 
+        For some variables, the program also computes the time average 
+        of the squared variables, which is used in other cdftools 
+        (cdfeke, cdfrmsssh, cdfstdevw, cdfstddevts ... The actual variables
+        selected for squared average are :
+          - vozocrtx
+          - vomecrty
+          - vovecrtz
+          - sossheig
+        This selection can be adapted with the nam_cdf_namelist process.
+        (See cdfnamelist -i for details).
+        If you want to compute the average of already averaged files,
+        consider using cdfmoy_weighted instead, in order to take into
+        account a particular weight for each file in the list.
+       
+      ARGUMENTS :
+        A list of similar model output files. 
+       
+      OPTIONS :
+        [ -spval0 ] :  set missing_value attribute to 0 for all output
+                variables and take care of the input missing_value.
+                This option is usefull if missing_values differ from files 
+                to files; it was formely done by cdfmoy_chsp).
+        [ -cub ] :  use this option if you want to compute third order moments
+                for the eligible variables, which are at present :
+               - sossheig
+               - votemper
+               This selection can be adapted with the nam_cdf_namelist process.
+               (See cdfnamelist -i for details).
+        [ -zeromean ] : with this option, the spatial mean value for each 
+               time frame is substracted from the original field before 
+               averaging, square averaging and eventually cubic averaging.
+        [-max ] : with this option, a file with the minimum and maximum values
+               of the variables is created.
+        [-nomissincl ] : with this option, the output mean is set to missing
+               value at any gridpoint where the variable contains a  missing
+               value for at least one timestep. You should combine with option
+               -spval0 if missing values are not 0 in all  the input files.
+        [ -nc4 ] Use netcdf4 output with chunking and deflation level 1
+                This option is effective only if cdftools are compiled with
+                a netcdf library supporting chunking and deflation.
+        [ -o output file root ] Default is cdfmoy
+       
+      REQUIRED FILES :
+        If -zeromean option is used, need mesh_hgr.nc and mask.nc
+       
+      OUTPUT : 
+        netcdf file : cdfmoy.nc and cdfmoy2.nc
+        variables : are the same than in the input files. For squared averages
+        _sqd is append to the original variable name.
+        If -cub option is used, the file cdfmoy3.nc is also created
+        with _cub append to the original variable name.
+        If -max option is used, file cdfmoy_minmax.nc is also created, with 
+        same variable names.
+       
+      SEE ALSO :
+        cdfmoy_weighted, cdfstdev
+       </code></pre>
+
+<h2 id="cdfmoy_freq">cdfmoy_freq</h2>
+
+<pre><code>  usage : cdfmoy_freq -i IN-file -f averaging-length [ -v3d] [-v4d] 
+               [-nc4] [-o output root] 
+       
+      PURPOSE :
+        This program takes a file covering 1 year of data (evenly spaced)
+        and sub-samples the data by performing box averages, which span is given
+        as argument.  The original data sampling can be hours, days or monthes 
+        or even seasons.
+        The program recognizes leap years, and when feb. 29 is found, it is 
+        included in the current 'box' (averaging length is thus increased
+        by 1 day.
+       
+      ARGUMENTS :
+        -i IN-file : gives the name of the yearly file containing either 365 
+                   or 366 days
+        -f averaging-length : Set the time size of the averaging box. 
+                  Averaging length is specified using XIOS convention (e.g. 1d,
+                  5d, 1mo, 1y ; 4mo stands for seasonal means )
+       
+      OPTIONS :
+        [-v3d] : use 3d variable (x,y,t) : save execution time, increase memory
+        [-v4d] : use 4d variable (x,y,z,t): save execution time, increase memory
+        [-nc4] : use netcdf4 with chunking and deflation for the output file
+        [-o output_root] : specify the root of the output file name instead 
+                    of cdfmoy_. Final name will have <freq> appened
+                    to the root.
+       
+      REQUIRED FILES :
+         none.
+       
+      OUTPUT : 
+        netcdf file :  cdfmoy_output<freq>.nc
+          variables :  same as variables in input file.
+       
+      SEE ALSO :
+       cdfmoy, cdfmoy_weighted
+       </code></pre>
+
+<h2 id="cdfmoy_weighted">cdfmoy_weighted</h2>
+
+<pre><code>  usage : cdfmoy_weighted list of files [-old5d ] [-month] [-leap] ...
+       [-skip variable] [-nc4] [-o output file]
+      PURPOSE :
+        Compute weight average of files. The weight for each file is
+        read from the iweight attribute. In particular, this attribute
+        is set to the number of elements used when computing a time
+        average (cdfmoy program). A primary application is thus for
+        computing annual mean from monthly means.
+       
+      ARGUMENTS :
+        The list of files to be averaged, which are supposed to be of
+        the same type and to contain the same variables. This list MUST
+        be given before any options
+       
+      OPTIONS :
+        [-old5d ] : This option is used to mimic/replace the cdfmoy_annual
+                    which is no longer available. With this option, 12 monthly
+                    files must be given, and it is assumed that the monthly
+                    means were computed from 5d output of a simulation using
+                    a noleap calendar ( weights are fixed, predetermined)
+        [-month ] : This option is used to build annual mean from true month
+                    output (1mo) in XIOS output for instance.
+        [-leap ] : This option has only effect together with the -month option.
+                   When used set 29 days in february
+        [-skip variable ] : name of variable to skip 
+        [ -nc4 ] : Use netcdf4 chunking and deflation in output file.
+        [-o output file ] : Specify the name for output file instead of the
+                  default name cdfmoy_weighted.nc
+       
+      REQUIRED FILES :
+        none
+       
+      OUTPUT : 
+        netcdf file : cdfmoy_weighted.nc
+        variables : same as in the input files</code></pre>
+
+<h2 id="cdfmoyt">cdfmoyt</h2>
+
+<pre><code>  usage : cdfmoyt list_of_model_files [-spval0]  
+      PURPOSE :
+        Compute the time average of a list of files given as arguments.
+        This program handle multi time-frame files is such a way that
+        the output files are also multi time-frame, each frame being
+        the average across the files given in the list.
+        
+        The program assume that all files in the list are of same
+        type (shape, variables , and number of time frames ). 
+        For some variables, the program also compute the time average 
+        of the squared variables, which is used in other cdftools 
+        (cdfeke, cdfrmsssh, cdfstdevw, cdfstddevts ... The actual variables
+        selected for squared average are :
+          - vozocrtx
+          - vomecrty
+          - vovecrtz
+          - sossheig
+        This selection can be adapted with the nam_cdf_namelist process.
+        (See cdfnamelist -i for details).
+        If you want to compute the average of already averaged files,
+        consider using cdfmoy_weighted instead, in order to take into
+        account a particular weight for each file in the list.
+       
+      ARGUMENTS :
+        A list of similar model output files. 
+       
+      OPTIONS :
+        [ -spval0 ] :  set missing_value attribute to 0 for all output
+                variables and take care of the input missing_value.
+                This option is usefull if missing_values differ from files 
+                to files; it was formely done by cdfmoy_chsp).
+       
+      REQUIRED FILES :
+        none 
+       
+      OUTPUT : 
+        netcdf file : cdfmoy.nc and cdfmoy2.nc
+        variables : are the same than in the input files. For squared averages
+        _sqd is append to the original variable name.</code></pre>
+
+<h2 id="cdfmoyuvwt">cdfmoyuvwt</h2>
+
+<pre><code>  usage : cdfmoyuv CONFCASE [-zoom imin imax jmin jmax ] 'list of tags' 
+       
+      PURPOSE :
+        Compute temporal mean fields for velocity components (u,v,w) and
+        temperature (t), as well as second order moments ( u2, v2, t2, uv, ut,
+        vt, wt).
+         These fields are required in other cdftools which computes either 
+         barotropic (cdfbti) or baroclinic (cdfbci) instabilities, and a global
+         energy balance (cdfnrjcomp)
+       
+      ARGUMENTS :
+        CONFCASE : the root name for the data files. Grid files are assumed to
+                   be gridT, gridU, gridV, gridW. ( grid_T, grid_U, grid_V and
+                   grid_W are also supported.
+        List_of_tags : The list of time tags corresponding to the time serie
+                   whose mean is being computed.
+       
+      OPTIONS :
+        [-zoom imin imax jmin jmax ] : limit the mean computation to the 
+                   specified sub area.
+       
+      REQUIRED FILES :
+        none
+       
+      OUTPUT : 
+        netcdf file : moyuvwt.nc
+          variables :  There are 11 variables produced by this program.
+                  tbar, t2bar : mean t (Kelvin) and mean t^2 (K^2)   [T-point]
+                  ubar, u2bar : mean u (m/s) and mean u^2 (m2/s2)    [U-point]
+                  vbar, v2bar : mean v (m/s) and mean v^2 (m2/s2)    [V-point]
+                  wbar        : mean w (m/s)                         [W-point]
+                  uvbar       : mean product u . v (m2/s2)           [T-point]
+                  utbar, vtbar, wtbar : mean product [uvw].t (m/s.K) [T-point]
+       
+      SEE ALSO :
+       cdfbti, cdfbci and cdfnrjcomp
+       </code></pre>
+
+<h2 id="cdfmppini">cdfmppini</h2>
+
+<pre><code>  usage : cdfmppini jpni jpnj [m/b/z] [-jperio jperio]
+       
+      PURPOSE :
+        Perform the mpp initialisation with NEMO routine mpp_init2 and
+        give some statistics about the domains. Save the layout on a 
+        text file.
+       
+      ARGUMENTS :
+        jpni : number of domains in the i direction.
+        jpnj : number of domains in the j direction.
+       
+      OPTIONS :
+        [m/b/z] : use one of these letter to choose the land/sea mask.
+                m  : take mask from mask.nc (tmask) [ default ]
+                b  : take mask from bathy_meter.nc (Bathymetry)
+                z  : take mask from mesh_zgr.nc (mbathy)
+                    Default is m
+        [-jperio jperio ] : specify jperio. 
+                          default value is  6
+       
+      REQUIRED FILES :
+        one of mask.nc, bathy_meter.nc or mesh_zgr.nc according to option
+       
+      OUTPUT : 
+        - Standard output
+        - ASCII file mppini.txt</code></pre>
+
+<h2 id="cdfmxl">cdfmxl</h2>
+
+<pre><code>  usage : cdfmxl T-file [S-file] [-nc4] [-o output file]
+       
+      PURPOSE :
+        Compute 7 estimates of the mixed layer depth from temperature
+        and salinity given in the input file, based on 3 different criteria:
+        1- Density criterium (0.01 kg/m3 difference between surface and MLD)
+        2- Density criterium (0.03 kg/m3 difference between surface and MLD)
+        3- Temperature criterium (0.2 C absolute difference between surface 
+           and MLD)
+        4- Temperature criterium (0.2 C absolute difference between T at 10m 
+           and MLD)
+        5- Temperature criterium (0.5 C absolute difference between T at 10m 
+           and MLD)
+        6- Density criterium (0.03 kg/m3 difference between rho at 10m and MLD) 
+        7- Density criterium (0.125 kg/m3 difference between rho at 10m and MLD)
+  
+       
+      ARGUMENTS :
+        T-file   : input netcdf file (gridT)
+        [S-file] : input netcdf file (gridS) Optional if vosaline not in T-file
+       
+      OPTIONS :
+        [-nc4] : use netcdf4 chunking and deflation on output 
+        [-o output file] : specify the name of output file instead of 
+                 default name mxl.nc
+       
+      REQUIRED FILES :
+         mesh_zgr.nc
+          In case of FULL STEP configuration, bathy_level.nc is also required.
+       
+      OUTPUT : 
+        netcdf file : mxl.nc
+          variables : somxl010    = mld on density criterium 0.01 ref. surf.
+                      somxl030    = mld on density criterium 0.03 ref. surf.
+                      somxlt02    = mld on temperature criterium -0.2 ref. surf.
+                      somxlt02z10 = mld on temperature criterium -0.2 ref. 10m
+                      somxlt05z10 = mld on temperature criterium -0.5 ref. 10m
+                      somxl030z10 = mld on density criterium 0.03 ref. 10m
+                      somxl125z10 = mld on density criterium 0.125 ref. 10m</code></pre>
+
+<h2 id="cdfmxlhcsc">cdfmxlhcsc</h2>
+
+<pre><code>  usage : cdfmxlhcsc T-file criteria value [hmin]
+       
+      PURPOSE :
+        Compute the mixed layer depth, the heat content and salt content.
+       
+      ARGUMENTS :
+        T-file : netcdf input file for temperature and salinity (gridT).
+        criteria : one of temperature, t,  T for temperature criteria.
+                   or density, d,  D  for density criteria.
+        value  : value of the criteria (eg: 0.2 for temp, 0.01 or 0.03 for dens)
+       
+      OPTIONS :
+        [ hmin ] : limit the vertical integral from hmin to mld. By default, 
+                   hmin is set to 0 so that the integral is performed on the
+                   whole mixed layer.
+       
+      REQUIRED FILES :
+        mesh_hgr.nc mesh_zgr.nc and mask.nc
+       
+      OUTPUT : 
+        netcdf file : mxlhcsc.nc
+          variables : -  somxl010 (mld based on density criterium 0.01)
+           (2D)          or somxl030 (mld on density criterium 0.03)
+                         or somxlt02 (mld on temperature criterium -0.2)
+                         -  somxlheatc (heat content computed in the MLD)
+                         -  somxlsaltc (salt content computed in the MLD)
+       
+      SEE ALSO :
+        cdfmxl, cdfmxlheatc and  cdfmxlsaltc.
+       </code></pre>
+
+<h2 id="cdfmxlheatc">cdfmxlheatc</h2>
+
+<pre><code>  usage : cdfmxlheatc T-file [-full]
+       
+      PURPOSE :
+        Computed the heat content in the mixed layer (Joules/m2).
+       
+      ARGUMENTS :
+        T-file : netcdf input file with temperature and mld (gridT).
+       
+      OPTIONS :
+        [ -full ] : for full step configurations, default is partial step.
+        [-o OUT-file ] : specify output file instead of mxlheatc.nc
+       
+       
+      REQUIRED FILES :
+        mesh_zgr.nc and mask.nc
+       
+      OUTPUT : 
+        netcdf file : mxlheatc.nc
+          variables : somxlheatc (Joules/m2)
+       
+      SEE ALSO :
+        cdfmxl, cdfmxlhcsc and  cdfmxlsaltc.
+       </code></pre>
+
+<h2 id="cdfmxlsaltc">cdfmxlsaltc</h2>
+
+<pre><code>  usage : cdfmxlsaltc T-file [-full ]
+       
+      PURPOSE :
+        Compute the salt content in the mixed layer.
+       
+      ARGUMENTS :
+        T-file : netcdf file with salinity and mixed layer deptht.
+       
+      OPTIONS :
+        [-full ] : indicate a full step configuration.
+        [-o OUT-file ] : specify output file instead of mxlsaltc.nc
+       
+      REQUIRED FILES :
+        mesh_zgr.nc and mask.nc
+       
+      OUTPUT : 
+        netcdf file : mxlsaltc.nc
+          variables : somxlsaltc (kg/m2 )
+       
+      SEE ALSO :
+        cdfmxl, cdfmxlhcsc, cdfmxlheatc 
+       </code></pre>
+
+<h2 id="cdfnamelist">cdfnamelist</h2>
+
+<pre><code>  usage :  cdfnamelist [-i] [-p]
+       
+      PURPOSE :
+        Give information [-i option] on the namelist mechanism implemented
+        in CDFTOOLS v3. Write a namelist template [-p option ] to initialize
+        the mechanism.
+       
+      ARGUMENTS :
+        none
+       
+      OPTIONS :
+        [ -i ] : print informations 
+        [ -p ] : write a template namelist.
+       
+      REQUIRED FILES :
+        none
+       
+      OUTPUT : 
+        with option -p, print a template namelist : PrintCdfNames.namlist
+       </code></pre>
+
+<h2 id="cdfnan">cdfnan</h2>
+
+<pre><code>  usage : cdfnan list_of_model_output_files [-value replace] [-absmax rabsmax ] 
+       
+      PURPOSE :
+        Detect NaN values in the input files, and change them to 
+        either spval (missing_value) or the value given as option.
+        Does the same for absolute values > huge(0.0)
+       
+      ARGUMENTS :
+        list of model output files. They must be of same type and have
+        similar sizes. CAUTION : input files are rewritten !
+       
+      OPTIONS :
+        [-value replace ] : use replace instead of missing_value for
+                            changing NaN.
+        [-absmax rabsmax ] : replace values whose absolute value is greater 
+                            than rabsmax.
+       
+      OUTPUT : 
+        netcdf file : input file is rewritten without NaN.
+          variables : same name as input.</code></pre>
+
+<h2 id="cdfnorth_unfold">cdfnorth_unfold</h2>
+
+<pre><code>  usage : cdfnorth_unfold IN-file jatl jpacif pivot Cgrid_point
+       
+      PURPOSE :
+        Unfold the Artic Ocean in an ORCA configuration. Produce a netcdf
+        file with the Artic ocean as a whole. The area can be adjusted on
+        both Atlantic and Pacific sides.
+       
+      ARGUMENTS :
+        IN-file     : netcdf file to be unfolded.
+        jatl        : J index to start the unfold process in the Atlantic.
+        jpacif      : J index to start the unfold process in the Pacific.
+        pivot       : type of pivot for the north fold condition ( T or F )
+        Cgrid_point : grid point where the variables in the input file are
+                      located. If all variables in a single file are not on
+                      the same C-grid location, there might be a problem ...
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        netcdf file : unfold.nc
+          variables : same name and units than in the input file.</code></pre>
+
+<h2 id="cdfnrjcomp">cdfnrjcomp</h2>
+
+<pre><code>  usage : cdfnrjcomp IN-file
+       
+      PURPOSE :
+        Compute contributing terms of the energy equation at T-points.
+        Input file contains mean values processed by cdfmoyuvwt.
+        The means must have been computed on long enough period
+        for the statistics to be meaningful
+       
+      ARGUMENTS :
+        IN-file   : netcdf file produced by cdfmoyuvwt.
+       
+      REQUIRED FILES :
+        none
+       
+      OUTPUT : 
+        netcdf file : nrjcomp.nc
+          all variables are located at T point.
+          variables : tbar : mean temperature 
+                      ubar : mean zonal velocity
+                      vbar : mean meridional velocity
+                      anotsqrt : mean squared temperature anomaly
+                      anousqrt : mean squared zonal velocity anomaly
+                      anovsqrt : mean squared meridional velocity anomaly</code></pre>
+
+<h2 id="cdfokubo-w">cdfokubo-w</h2>
+
+<pre><code>  usage : cdfokubow U-file V-file U-var V-var lev
+       
+      PURPOSE :
+        Compute Okubo-Weiss parameter of a vector field, at a specified level.
+        If level is specified as 0, assume that the input files are
+        forcing files, presumably on A-grid. In this latter case, the
+        vector field is interpolated on the C-grid. In any case, the
+        curl is computed on the F-point.
+       
+      ARGUMENTS :
+        U-file : zonal component of the vector field.
+        V-file : meridional component of the vector field.
+        U-var  : zonal component variable name
+        V-var  : meridional component variable name.
+        lev    : level to be processed. If set to 0, assume forcing file 
+                 in input.
+       
+      REQUIRED FILES :
+         mesh_hgr.nc and mask.nc
+       
+      OUTPUT : 
+        netcdf file : okubow.nc
+          variables : sokubow (s^-2)</code></pre>
+
+<h2 id="cdfovide">cdfovide</h2>
+
+<pre><code> usage : cdfovide gridTfile gridUfile gridVfile 
+      Files mesh_hgr.nc and mesh_zgr.nc must be in te current directory 
+      Output on netcdf file ovide.nc</code></pre>
+
+<h2 id="cdfpendep">cdfpendep</h2>
+
+<pre><code>  usage :  cdfpendep TRC-file INV-file  ... 
+                     ... [-inv inventory_name -trc trc_name ]
+       
+      PURPOSE :
+         Compute the penetration depth for passive tracers. It is the
+         ratio between the inventory and the surface concentration of
+         the tracer.
+       
+      ARGUMENTS :
+        TRC-file : netcdf file with tracer concentration.
+        INV-file : netcdf file with inventory of the tracer.
+       
+      OPTIONS :
+        [-inv inventory_name ] : specify netcdf variable name for inventory.
+                                 Default is INVCFC
+        [-trc tracer_name ]    : specify netcdf variable name for tracer.
+                                 Default is CFC11
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        netcdf file : pendep.nc
+          variables : pendep (m)</code></pre>
+
+<h2 id="cdfpolymask">cdfpolymask</h2>
+
+<pre><code>  usage : cdfpolymask -p POLY-file -ref REF-file [ -r] [-o OUT_file]
+       
+      PURPOSE :
+        Create a maskfile with polymask variable having 1
+        inside the polygon, and 0 outside. Option -r revert
+        the behaviour (0 inside, 1 outside).
+       
+      ARGUMENTS :
+        -p POLY-file : input ASCII file describing a polyline in I J grid.
+             This file is structured by block, one block corresponding 
+             to a polygon:
+               1rst line of the block gives a polygon name
+               2nd line gives the number of vertices (nvert) and a dummy 0
+               the block finishes  with nvert pairs of (I,J) describing 
+               the polygon vertices.
+        -ref REF-file  : reference netcdf file for header of polymask file.
+              This file will be used to look for domain dimensions, and 
+              in order to build the output file (nav_lon, nav_lat etc ...)
+       
+      OPTIONS :
+         [ -r ] : revert option. When used, 0 is inside the polygon,
+                  1 outside.
+         [ -o OUT-file ] : spefify the name of the output mask file instead
+                  of polymask.nc
+       
+      REQUIRED FILES :
+        none
+       
+      OUTPUT : 
+        netcdf file : polymask.nc
+          variables : polymask</code></pre>
+
+<h2 id="cdfprobe">cdfprobe</h2>
+
+<pre><code>  usage :  cdfprobe IN-file ilook jlook cdfvar [level]
+       
+      PURPOSE :
+       Display a 2 columns output time (in days), value.
+       
+      ARGUMENTS :
+        IN-file : input file to look for
+        ilook jlook : i,j position of the probe.
+        cdfvar : name of the cdf variabled to be displayed
+       
+      OPTIONS :
+        [level] : This optional last argument is used
+                to specify a model level, instead of first.
+       
+      REQUIRED FILES :
+        none
+       
+      OUTPUT : 
+        2 columns ( time , value ) ASCII output on display
+        time are given in days since the begining of the run.</code></pre>
+
+<h2 id="cdfprofile">cdfprofile</h2>
+
+<pre><code>  usage : cdfprofile  I J IN-file IN-var [-dep depth ]
+       
+      PURPOSE :
+        Extract a vertical profile at location I J, for a variable
+        in an input file.
+       
+      ARGUMENTS :
+        I   J   : I, J position of the point to extract from file.
+        IN-file : input file to work with.
+        IN-var  : variable name whose profile is requested.
+       
+      OPTIONS :
+        -dep depth : specify a depth where vertical value will be
+                      interpolated.
+       
+      REQUIRED FILES :
+         none 
+       
+      OUTPUT : 
+        netcdf file : profile.nc
+           variable : name given as argument.
+        Profile is also written on standard output.</code></pre>
+
+<h2 id="cdfpsi">cdfpsi</h2>
+
+<pre><code>  usage : cdfpsi U-file V-file [V] [-full ] [-mask ] [-mean] [-nc4 ] ...
+           ... [-ssh T-file ] [-open ] [-ref iref jref ] [-o OUT-file]
+       
+      PURPOSE :
+        Computes the barotropic stream function (a proxy ) as the integral of 
+        the transport.
+       
+      ARGUMENTS :
+        U-file  : netcdf file of zonal velocity.
+        V-file  : netcdf file of meridional velocity.
+       
+      OPTIONS :
+        [V] : use V field instead of U field for integration.
+        [ -full ] : indicates a full step case. Default is partial steps.
+        [ -mask ] : mask output fields. Note that the land value is significant.
+                    It correspond to the potential on this continent.
+        [ -mean ] : save the average of the computations done with U and V.
+        [ -nc4  ] : use netcdf4 output files with chunking and deflation
+        [ -ssh T-file ] : compute the transport in the 'ssh' layer, using 
+                   surface velocities. Take the ssh from T-file specified in 
+                   this option. This is a experimental option, not certified ...
+        [ -open ] : for open domain configuration. See also -ref to set 
+                    reference point.
+        [ -ref iref jref ] : Set the reference point in i,j coordinates.
+                    BSF at reference point is arbitrarly set to zero.
+        [ -o  OUT-file ] : specify output file name instead of default psi.nc
+       
+      REQUIRED FILES :
+        mesh_hgr.nc and mesh_zgr.nc.
+        mask.nc is required only if -mask option used.
+       
+      OUTPUT : 
+        netcdf file : psi.nc
+          variables : sobarstf (m3/s )
+        If option -ssh is used, 2 additional variables are added to the file :
+                      sobarstfssh (m3/s ) : contribution of SSH
+                      sobarstftotal (m3/s ) : total BSF
+       </code></pre>
+
+<h2 id="cdfpsi_level">cdfpsi_level</h2>
+
+<pre><code>  Usage : cdfpsi_level  Ufile Vfile <V> (optional argument)
+  Computes the barotropic stream function as the integral of the transport
+  PARTIAL CELLS VERSION
+  Files mesh_hgr.nc, mesh_zgr.nc ,mask.nc must be in te current directory
+  Output on psi_level.nc, variables sobarstf on f-points
+  Default works well for a global ORCA grid. use V 3rdargument for North Atlanti
+ c</code></pre>
+
+<h2 id="cdfpvor">cdfpvor</h2>
+
+<pre><code>  usage : cdfpvor T-file  U-file V-file [-full] [-lspv ] [-nc4] [-o output file]
+       
+      PURPOSE :
+        Compute the Ertel potential vorticity and save the relative  
+        vorticity, the stretching and the total potential vorticity. 
+        Qtot = ( f + xsi ) . D(rho)/D(z)  = Qstrech + Qrel           
+        With -lspv option, compute only Qstretch or Large Scale P V 
+       
+      ARGUMENTS :
+        T-file : netcdf file for temperature and salinity.           
+        U-file : netcdf file for zonal component of the velocity.    
+        V-file : netcdf file for meridional component of the velocity.
+       
+      OPTIONS :
+        [-full ] : indicate a full step configuration.                
+        [-lspv ] : calculate only the large scale potential vorticity.
+                   ( replace the old cdflspv tool).
+                   If used only T-file is required, no need for velocities.
+        [-nc4 ] :  use netcdf4 with chunking and deflation 
+        [-o output file ] : use output file instead of default pvor.nc
+       
+      REQUIRED FILES :
+        mesh_hgr.nc and mesh_zgr.nc
+       
+      OUTPUT : 
+        netcdf file : pvor.nc
+          variables : vorelvor (1.e-7 kg.m-4.s-1 ) relative vorticity
+                      vostrvor (1.e-7 kg.m-4.s-1 ) stretching vorticity
+                      vototvor (1.e-7 kg.m-4.s-1 ) total potential vorticity
+                   Ertel PV are located at T points.
+            
+        With option -lspv :
+        netcdf file : lspv.nc
+          variables :  volspv  (1.e-7 kg.m-4.s-1 ) large scale potential vortici
+ ty
+                   LSPV is  located at W points.
+       
+      SEE ALSO :
+        cdfcurl ( compute only the curl on 1 level)
+       </code></pre>
+
+<h2 id="cdfrhoproj">cdfrhoproj</h2>
+
+<pre><code>  usage : cdfrhoproj IN-var RHO-file List_of_IN-files [VAR-type] [-debug ]... 
+        ... [-isodep] [-s0 sig0 | -s0 sigmin,sigstp,nbins ] [-sig sigma_name]..
+        ... [-noiso]
+       
+      PURPOSE :
+        Project IN-var on isopycnal surfaces. The isosurfaces can be defined in
+        many ways : (1) In a pre-defined ASCII file named rho_levsee format
+        below.  (2) using -s0 option.
+        IN-var will be interpolated on the T point of the C-grid, previous
+        to projection on isopycnal.
+        
+        WARNING: This cdftool is one of the few using 3D arrays. Further 
+        development is required to work with vertical slabs instead.
+       
+      ARGUMENTS :
+        IN-var   : name of the input variable to be projected
+        RHO-file : netcdf file with potential density field. If not a sigma0
+                   file, use -sig option to indicate the name of the density
+                   variable.
+        List_of_IN-file  : netcdf files with IN-var 
+       
+      OPTIONS :
+        [-s0 sigma  | -s0 sigmin,sigstp,nbins ]  : In the first form define a 
+                     single sigma surface on the command line, while in the 2nd
+                     form, it uses the same numbers than cdfmocsig to define
+                     equally spaced (sigstp) density surfaces, starting from 
+                     sigmin and up to sigmin + (nbins)*sigstp
+                     This option prevails the use of rho_lev file.
+        [VAR-type] : position of IN-var on the C-grid ( either T U V F W S )
+                     default is 'T'. 
+                     S is used in case of section files (cdf_xtract_brokenline).
+        [-sig sigma_name] : name of the density variable in RHO_file.
+                     default is vosigma0
+        [-isodep ] : only compute the isopycnal depth. then stop. In this case
+                     you must still specify a IN-var variable (in fact a dummy
+                      name).
+        [-noiso]   : do not save isopycnal depth (suitable for big files).
+        [-debug]   : produce extra prints. Must be use before other options ..
+       
+      REQUIRED FILES :
+        no metrics, information is taken from depth variable in input files.
+        rho_lev if not using -s0 option.
+        rho_lev is an ascii file, first line giving the number of isopycnal
+                            following lines with isopycnal value, 1 per line.
+       
+      OUTPUT : 
+        There are as many output files as input files.
+        netcdf file : IN-file.interp
+          variables : VAR-in (unit is the same as input var)
+                      vodepiso (m) : depth of isopycnal.
+       
+        If option -isodep is used, only isopycnal depth is output :
+        netcdf file : isopycdep.nc
+          variables : vodepiso (m) 
+       
+      SEE ALSO :
+        replace cdfisopycdep when using -isodep option,  cdfmocsig
+        </code></pre>
+
+<h2 id="cdfrichardson">cdfrichardson</h2>
+
+<pre><code>  usage : cdfrichardson  gridT gridU gridV [ W ] [-full]
+      PURPOSE :
+        Compute the Richardson Number (Ri) according to
+        temperature, salinity and velocity components
+        given in the input files.
+       
+      ARGUMENTS :
+        gridT : input gridT file for temperature and salinity
+        gridU : input gridU file for zonal velocity component
+        gridV : input gridV file for meridional velocity component
+       
+      OPTIONS :
+        [ W ] : keep N2 at W points. Default is to interpolate N2
+              at T point on the vertical
+        [ -full ] : indicate a full step configuration instead of
+                 the default partial steps.
+       
+      REQUIRED FILES :
+        mesh_zgr.nc is needed for this program.
+       
+      OUTPUT : 
+        netcdf file : richardson.nc
+        variables : voric</code></pre>
+
+<h2 id="cdfrmsssh">cdfrmsssh</h2>
+
+<pre><code>  usage : cdfrmsssh T-file T2-file [-nc4] [-o outputfile]
+       
+      PURPOSE :
+        Compute the standard deviation of the SSH from its
+        mean value and its mean square value. 
+       
+        Note that what is computed in this program is stictly the
+        standard deviation. It is very often called RMS, which is
+        an abuse. It is the same only in the case of zero mean value.
+        However, for historical reason, the name of this tool, remains
+        unchanged: cdfrmsssh
+       
+      ARGUMENTS :
+        T-file  : netcdf file with mean values for SSH
+        T2-file : netcdf file with mean squared values for SSH
+       
+      OPTIONS :
+        [-nc4] : use netcdf4 with chunking and deflation 
+        [-o output file ] : specify the name of the output file instead
+                           of default name rms.nc
+       
+      REQUIRED FILES :
+        none
+       
+      OUTPUT : 
+        netcdf file : rms.nc
+          variables : sossheig_rms, same unit than the input.
+       
+      SEA ALSO :
+        cdfstd, cdfstdevw, cdfstdevts.</code></pre>
+
+<h2 id="cdfscale">cdfscale</h2>
+
+<pre><code>  usage : cdfscale INOUT-file IN-var scale 
+       
+      PURPOSE :
+        Replace IN-var in INOUT-file by its values x scale.
+       
+      ARGUMENTS :
+        INOUT-file : netcdf input file (!overwritten!).
+        IN-var : netcdf variable to be scaled.
+        scale : Scale value to be used (multiplication factor).
+       
+      OUTPUT : 
+        netcdf file : input file is rewritten 
+          variables : same name as input.</code></pre>
+
+<h2 id="cdfsections">cdfsections</h2>
+
+<pre><code> Usage : 
+  cdfsections  Ufile Vfile Tfile larf lorf Nsec lat1 lon1 lat2 lon2 n1
+               [ lat3 lon3 n2 ] [ lat4 lon4 n3 ] ....
+    
+  Computes temperature, salinity, sig0, sig1, sig2, sig4, Uorth, Utang 
+  along a section made of Nsec linear segments (see output attributes).
+  Output is section.nc, var. as a function of X(km), depth(m) and time.
+    
+ Arguments : 
+  # larf and lorf -> location of X=0 for the X-absice (may be out of section)
+  # Nsec -> number of segments used to compute the whole section.
+  # lat1,lat2,lat3,... -> extrema latitudes of the segments (from -90 to 90)
+  # lon1,lon2,lon3,... -> extrema latitudes of the segments (from 0 to 360)
+  # n1, n2, ...        -> number of output points on each segment.
+    (you have to give Nsec+1 values of lati/loni and Nsec values of ni)
+  
+  It is recommended to put a lot of points on each section if the aim
+  is to compute X-integrations along the section (10 x the model resolution).
+ NB : sections cannot cross the Greenwich line !!
+ NB : Not yet tested north of 60N.
+ NB : require a large amount of memory !
+      -> reduce domain size with  ncks -d  if insufficient memory error.
+  
+ Example for one linear section : 
+  cdfsections U.nc V.nc T.nc 48.0 305.0 1 49.0 307.0 50.5 337.5 20
+ Example for a section made of 2 linear segments : 
+  cdfsections U.nc V.nc T.nc 48.0 305.0 2 49.0 307.0 50.5 337.5 20 40.3 305.1 50</code></pre>
+
+<h2 id="cdfsig0">cdfsig0</h2>
+
+<pre><code>  usage : cdfsig0 -t T-file [-sal SAL-name] [-tem TEM-name] [-nc4] [-o OUT-file]
+       
+      PURPOSE :
+        Compute potential density (sigma-0) refered to the surface.
+       
+      ARGUMENTS :
+        -t T-file  : netcdf file with temperature and salinity.
+          (for backward compatibility, -t can be ommited when T-file is the only
+          argument.)
+       
+      OPTIONS :
+        [-sal SAL-name]  : name of salinity variable
+        [-tem TEM-name]  : name of temperature variable
+        [-nc4]  : enable chunking and compression
+        [-o OUT-file]    : specify output filename instead of sig0.nc
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        netcdf file : sig0.nc
+          variables : vosigma0 ( kg/m3 - 1000 )
+       
+      SEE ALSO :
+        cdfsigi</code></pre>
+
+<h2 id="cdfsigi">cdfsigi</h2>
+
+<pre><code>  usage : cdfsigi T-file Ref-dep(m) 
+       
+      PURPOSE :
+        Compute potential density refered to the depth given in arguments.
+       
+      ARGUMENTS :
+        T-file : netcdf file with temperature and salinity
+        Ref-dep : reference depth in meter.
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        netcdf file : sigi.nc
+          variables : vosigmai (kg/m3 -1000 )
+       
+      SEE ALSO :
+       cdfsig0
+       </code></pre>
+
+<h2 id="cdfsiginsitu">cdfsiginsitu</h2>
+
+<pre><code>  usage : cdfsiginsitu -t T-file [-sal SAL-name] [-tem TEM-name ] ...
+                 [-dep depth] [-o OUT-file ] [-nc4 ] 
+       
+      PURPOSE :
+        Compute in situ density from temperature and salinity.
+        Depths are taken from input file.
+       
+      ARGUMENTS :
+        -t T-file : netcdf file with temperature and salinity.
+          (for backward compatibility, -t can be ommited when T-file is the only
+          argument.)
+       
+      OPTIONS :
+        [-sal SAL-name] : name of salinity variable
+        [-tem TEM-name] : name of temperature variable
+        [-dep depth ]   : depth to be used in case of 2D input file (only)
+        [-nc4]          : enable chunking and compression
+        [-o OUT-file]   : specify output filename instead of siginsitu.nc
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        netcdf file : siginsitu.ncor the file name specified 
+                    with -o option
+          variables : vosigmainsitu (kg/m3 -1000 )
+       
+      SEE ALSO :
+       cdfsig0, cdfsigi 
+       </code></pre>
+
+<h2 id="cdfsigintegr">cdfsigintegr</h2>
+
+<pre><code>  usage : cdfsigintegr IN-var RHO-file list_of_files [ VAR-type ] ...
+               ... [ -sig sigma_name] [ -full ] 
+       
+      PURPOSE :
+        Take a list of input files with specific IN-var variable, associated
+        with a reference density file. A set of isopycnal surfaces is defined
+        in an ASCII file (rho_lev by default), using same depth reference than
+        the input reference density file. This program computes the integral of
+        IN-var between the isopycnals defined in rho_lev. It also gives the 
+        isopycnal depth and thickness of density layers.
+       
+        Rho_lev file first line indicates the number of following isopycnals.
+        Then a list of the densities is given, one per line.
+       
+      ARGUMENTS :
+        IN-var : input variable to be integrated
+        RHO-file : netcdf file with already computed density
+        list_of_files : a list of model netcdf files containing IN-var.
+       
+      OPTIONS :
+        [ VAR-type ] : one of T U V F W which defined the position on
+                IN-var in the model C-grid. Default is T
+        [ -sig sigma_name ] : give the name of sigma variable in RHO-file.
+                Default is vosigma0
+        [ -full ] : indicate a full step configuration.
+        [ -rholev  file] : indicates name of file defining the limits for 
+                integration. Default is rho_lev
+       
+      REQUIRED FILES :
+        mesh_zgr.nc and rho_lev
+       
+      OUTPUT : 
+        netcdf file : IN-file.integr
+          variables : inv_IN-var  : inventory of IN-var from input file.
+                      vodepiso (m) : depth of isopycnal.
+                      isothick (m) : thickness of isopycnal layer.
+                      mean_IN-var (same unit as IN-var) : mean IN-var in the iso
+ pycnal
+       
+      SEE ALSO :
+       cdfrhoproj, cdfsigtrp, cdfisopycdep
+       </code></pre>
+
+<h2 id="cdfsigntr">cdfsigntr</h2>
+
+<pre><code>  usage : cdfsigntr T-file
+       
+      PURPOSE :
+        Compute neutral volumic mass (kg/m3) from temperature and salinity.
+       
+      ARGUMENTS :
+        T-file  : netcdf file with temperature and salinity.
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        netcdf file : signtr.nc
+          variables : vosigntr ( kg/m3 )
+       
+      SEE ALSO :
+        cdfsig0, cdfsigi, cdfsiginsitu</code></pre>
+
+<h2 id="cdfsigtrp">cdfsigtrp</h2>
+
+<pre><code>  usage :  cdfsigtrp T-file U-file V-file sigma_min sigma_max nbins ...
+               ... [-print ] [-bimg ] [-full ] [ -refdep ref_depth] ...
+               ... [-neutral ] [-section file ] [-temp ]
+       
+      PURPOSE :
+        Compute density class transports, according to the density class
+        definition ( minimum, maximum and number of bins) given in arguments.
+        Section position are given in dens_section.dat, an ASCII file 
+        with pairs of lines giving section name and section location as
+        imin imax jmin jmax. Only zonal or meridional section are allowed.
+        The name of this file can be specified with the -section option, if
+        it differs from the standard name. Optionaly, a netcdf root variable 
+        name and a netcdf root long-name can be provided on the line giving 
+        the section name.
+       
+        This program can also be used to compute transport by class of 
+        temperatures, provided the temperatures decrease monotonically 
+        downward. In this case, use -temp option and of course specify
+        sigma_min, sigma_max as temperatures.
+       
+      ARGUMENTS :
+        T-file : netcdf file with temperature and salinity
+        U-file : netcdf file with zonal velocity component
+        V-file : netcdf file with meridional velocity component
+        sigma_min : minimum density for binning
+        sigma_max : maximum density for binning
+        nbins : number of bins. This will fix the bin 'width' 
+       
+      OPTIONS :
+        [ -full ] : for full step configuration
+        [ -bimg ] : produce extra bimg output file which shows the details
+                of the sections (normal velocity, density, temperature, 
+                salinity, transports, isopycnal depths. (to be change to 
+                netcdf files for more common use.
+        [ -ncdf ] : produce extra netcdf output file which shows the details
+                of the sections (normal velocity, density, temperature, 
+                salinity, transports, isopycnal depths. 
+        [ -print ]: write the binned transports on standard output, for each
+                sections.
+        [ -refdep ref_depth ]: give a reference depths for the computation of
+                potential density. Sigma_min, sigma_max must be adapted 
+                accordingly.
+        [ -neutral ]: use neutral density instead of potential density 
+        [ -section file] : give the name of section file.
+                Default is dens_section.dat
+        [ -temp ] : use temperature instead of density for binning
+       
+      REQUIRED FILES :
+        mesh_hgr.nc, mesh_zgr.nc and dens_section.dat
+       
+      OUTPUT : 
+        Netcdf file : There is 1 netcdf file per section. File name is build
+          from section name : Section_name_trpsig.nc
+          variables : sigma_class (upper limit of the bin)
+                      sigtrp : transport (Sv per bin)
+       
+        ascii file  : trpsig.txt
+       
+        bimg  file  :  There are 2 bimg files whose name is build from section
+          name : section_name_trpdep.bimg and section_name_trpsig.bimg.
+          This file is written only if -bimg option is used.
+       
+       Standard output : the results are written on standard output only if 
+          the -print option is used.
+       
+      SEE ALSO :
+       cdfrhoproj, cdftransport, cdfsigintegr 
+       </code></pre>
+
+<h2 id="cdfsigtrp_broken">cdfsigtrp_broken</h2>
+
+<pre><code>  usage :  cdfsigtrp_broken TSV-file sigma_min sigma_max nbins ...
+               ... [-print ] [-bimg ] [-full ] [ -refdep ref_depth] ...
+               ... [-neutral ] [-section file ] [-temp ]
+       
+      PURPOSE :
+        Compute density class transports, according to the density class
+        definition ( minimum, maximum and number of bins) given in arguments.
+        Section position are given in dens_section.dat, an ASCII file 
+        with pairs of lines giving section name and section location as
+        imin imax jmin jmax. Only zonal or meridional section are allowed.
+        The name of this file can be specified with the -section option, if
+        it differs from the standard name. Optionaly, a netcdf root variable 
+        name and a netcdf root long-name can be provided on the line giving 
+        the section name.
+        In this particular tool, the section used is the result of 
+        cdf_xtrac_brokenline. In this way, it is possible to calculate the
+        transport of density class in oblicous sections (non dependance on 
+        zonal or meridional).
+       
+        This program can also be used to compute transport by class of 
+        temperatures, provided the temperatures decrease monotonically 
+        downward. In this case, use -temp option and of course specify
+        sigma_min, sigma_max as temperatures.
+       
+      ARGUMENTS :
+        TSV-file : netcdf_broken_line file with temperature, salinity
+        and the normal velocity through the section
+        sigma_min : minimum density for binning
+        sigma_max : maximum density for binning
+        nbins : number of bins. This will fix the bin 'width' 
+       
+      OPTIONS :
+        [ -full ] : for full step configuration
+        [ -bimg ] : produce extra bimg output file which shows the details
+                of the sections (normal velocity, density, temperature, 
+                salinity, transports, isopycnal depths. (to be change to 
+                netcdf files for more common use.
+        [ -ncdf ] : produce extra netcdf output file which shows the details
+                of the sections (normal velocity, density, temperature, 
+                salinity, transports, isopycnal depths. 
+        [ -print ]: write the binned transports on standard output, for each
+                sections.
+        [ -refdep ref_depth ]: give a reference depths for the computation of
+                potential density. Sigma_min, sigma_max must be adapted 
+                accordingly.
+        [ -neutral ]: use neutral density instead of potential density 
+        [ -section file] : give the name of section file.
+                Default is dens_section.dat
+        [ -temp ] : use temperature instead of density for binning
+       
+      REQUIRED FILES :
+        mesh_zgr.nc and dens_section.dat
+       
+      OUTPUT : 
+        Netcdf file : There is 1 netcdf file per section. File name is build
+          from section name : Section_name_trpsig.nc
+          variables : sigma_class (upper limit of the bin)
+                      sigtrp : transport (Sv per bin)
+       
+        ascii file  : trpsig.txt
+       
+        bimg  file  :  There are 2 bimg files whose name is build from section
+          name : section_name_trpdep.bimg and section_name_trpsig.bimg.
+          This file is written only if -bimg option is used.
+       
+       Standard output : the results are written on standard output only if 
+          the -print option is used.
+       
+      SEE ALSO :
+       cdfrhoproj, cdftransport, cdfsigintegr, cdfsigtrp, cdf_xtrac_brokenline 
+       </code></pre>
+
+<h2 id="cdfsmooth">cdfsmooth</h2>
+
+<pre><code>  usage : cdfsmooth -f IN-file -c ncut [-t filter_type] [ -k level_list ] ...
+        [-a anisotripoc ratio ] [-nc4 ] 
+       
+      PURPOSE :
+        Perform a spatial smoothing on the file using a particular
+        filter as specified in the option. Available filters
+        are : Lanczos, Hanning, Shapiro, Box car average. Default
+        is Lanczos filter.
+       
+      ARGUMENTS :
+        -f  IN-file  : input data file. All variables will be filtered
+        -c  ncut     : number of grid step to be filtered, or number
+                     of iteration of the Shapiro filter.
+       
+      OPTIONS :
+        -t filter_type : Lanczos      , L, l  (default)
+                         Hanning      , H, h
+                         Shapiro      , S, s
+                         Box          , B, b
+        -a aniso       : anisotropic ratio for Box car 
+        -k level_list  : levels to be filtered (default = all levels)
+                level_list is a comma-separated list of levels.
+                   the syntax 1-3,6,9-12 will select 1 2 3 6 9 10 11 12
+        -nc4 : produce netcdf4 output file with chunking and deflation.
+       
+      OUTPUT : 
+        Output file name is build from input file name with indication
+        of the filter type (1 letter) and of ncut.
+        netcdf file :   IN-file[LHSB]ncut
+          variables : same as input variables.</code></pre>
+
+<h2 id="cdfspeed">cdfspeed</h2>
+
+<pre><code>  usage : cdfspeed  U-file V-file U-var V-var [-t T-file] ...
+             ... [-nc4] [-o OUT-file ] [-lev level_list]
+     PURPOSE :
+        Computes the speed of ocean currents or wind speed
+        
+        If the input files are 3D, the input is assumed to be 
+        a model output on native C-grid. Speed is computed on the A-grid.
+        
+        If the input file is 2D and then we assume that this is 
+        a forcing file already on the A-grid.
+     
+     ARGUMENTS :
+        U-file : netcdf file for U component
+        V-file : netcdf file for V component
+        U-var  : netcdf variable name for U component
+        V-var  : netcdf variable name for V component
+     
+     OPTIONS :
+        -t T-file  : indicate any file on gridT for correct header
+                  of the output file (usefull for 3D files)
+        -lev level_list  : indicate a list of levels to be processed
+                  If not used, all levels are processed.
+                  This option should be the last on the command line
+        -nc4 : use netcdf4 output with chunking and deflation
+        -o OUT-file : use specified output file instead of speed.nc
+     
+     OUTPUT :
+        Output on speed.nc  variable U </code></pre>
+
+<h2 id="cdfspice">cdfspice</h2>
+
+<pre><code>  usage : cdfspice -t T-file [-sal SAL-name] [-tem TEM-name] ...
+         ... [-nc4] [-o OUT-file]
+       
+      PURPOSE :
+        Compute the spiceness corresponding to temperatures and salinities
+        given in the input file.
+       
+        spiciness = sum(i=0,5)[sum(j=0,4)[b(i,j)*theta^i*(s-35)^j]]
+                  with:  b     -> coefficients
+                         theta -> potential temperature
+                         s     -> salinity
+       
+      ARGUMENTS :
+        -t T-file : netcdf file with temperature and salinity (gridT)
+            Single argument T-file can also be used, for backward compatibility
+      
+      OPTIONS :
+        [-sal SAL-name]  : name of salinity variable
+        [-tem TEM-name]  : name of temperature variable
+        [-nc4]  : enable chunking and compression
+        [-o OUT-file]    : specify output filename instead of spice.nc
+       
+      REQUIRED FILES :
+        none
+       
+      OUTPUT : 
+        netcdf file : spice.nc
+          variables : vospice
+       
+      REFERENCE :
+        Flament (2002) "A state variable for characterizing 
+              water masses and their diffusive stability: spiciness."
+              Progress in Oceanography Volume 54, 2002, Pages 493-501.</code></pre>
+
+<h2 id="cdfsstconv">cdfsstconv</h2>
+
+<pre><code>  Usage : cdfflxconv YEAR config 
+     Output 6 cdf files : for emp, qnet, qsr, sst, taux, tauy with standard var 
+ name :
+         sowaflup, sohefldo, soshfldo, sst, sozotaux, sometauy 
+     coordinates.diags ( clipper like) is required in current dir </code></pre>
+
+<h2 id="cdfstatcoord">cdfstatcoord</h2>
+
+<pre><code>  usage : cdfstatcoord COOR-file MSK-file [ MSK-var ]
+       
+      PURPOSE :
+        Computes and displays statistics about grid metrics vs latitude.
+        Bins e1 and e2 by latitude bins, and compute the mean of each bin.
+       
+      ARGUMENTS :
+        COOR-file : coordinates file with e1 e2 metrics
+        MSK-file  : mask file 
+       
+      OPTIONS :
+        [MSK-var] : mask variable name. Default is tmask
+       
+      REQUIRED FILES :
+        none apart those requested on command line.
+       
+      OUTPUT : 
+        Standard output</code></pre>
+
+<h2 id="cdfstats">cdfstats</h2>
+
+<pre><code>  usage : cdfstats IN-file REF-file ncy [VAR-name1 [VAR-name2]] ...
+                 [-m mesh_mask file ]
+       
+      PURPOSE :
+             This tool computes some statistics (rms, correlation, 
+          signal/noise ratio and signal ratio [ratio of std 
+          deviation]) between to files. In this tool, the files
+          are supposed to hold monthly averages values, for many 
+          years. Specifying ncy=12, allows to remove the seasonal
+          cycle of the data.
+             This program was initially written for SSH statistics
+          between model output and AVISO files (default variable
+          names are sossheig for this reason ). It can
+          now be used with any variables.
+       
+      ARGUMENTS :
+         IN-file  : First data file ( usually model output) 
+         REF-file : Second data file ( usually observation file) 
+         ncy      : 1 or 12. If set to 12, annual cycle is removed 
+                    from the data 
+         [VAR-name1 [VAR-name2]] : If variable names of input files
+                  are not sossheig they can be specified
+                  on the command line. If only one name is given, it is
+                  assumed that both file use same variable name.
+       
+      OPTIONS :
+         -m mesh_mask file : specify a mesh_mask file holding the tmaskutil
+                  and the horizontal metrics. If this option is not used,
+                  mask are taken in mask.nc and horizontal metric
+                  is taken in mesh_hgr.nc
+       
+      REQUIRED FILES :
+        mask.nc and mesh_hgr.nc
+            or mesh_mask file specified in -m option
+       
+      OUTPUT : 
+         netcdf file : stats.nc
+          variables are : 
+                rms    : RMS between the input files
+                correl : CORREL between the input files
+                rrat   : Signal to noise ratio 
+                srat   : Signal ratio (stdev ratio) 
+       </code></pre>
+
+<h2 id="cdfstd">cdfstd</h2>
+
+<pre><code>  usage : cdfstd [-save] [-spval0] [-nomissincl] [-stdopt] list_of files 
+       
+      PURPOSE :
+        Compute the standard deviation of the variables belonging to a set of
+        files given as arguments.  This computation is direct and does not 
+        required a pre-processing with any of the cdfmoy tools.
+       
+      ARGUMENTS :
+        List on netcdf files of the same type, forming a time-series
+       
+      OPTIONS :
+        [ -save ] : Save the mean value of the field, in addition to the 
+            std deviation. If used must be appear before list of files.
+        [ -spval0 ] :  set missing_value attribute to 0 for all output
+            variables and take care of the input missing_value.
+            This option is usefull if missing_values differ from files 
+            to files.
+            If used it should be called  before the list of input files.
+        [-nomissincl ] : with this option, the output std and mean are set to
+            missing value at any gridpoint where the variable contains a 
+            missing value for at least one timestep. You should combine 
+            with -spval0 if missing values are not 0 in all the input files.
+            If used it should be called  before the list of input files.
+        [ -stdopt ]:  use a  more optimal algorithm to compute std
+            and std is unbiased.  If used it should be called  before
+             the list of input files.
+       
+      REQUIRED FILES :
+        none
+       
+      OUTPUT : 
+        - netcdf file : cdfstd.nc
+            variables :  IN-var_std, same units than input variables.
+        - netcdf file : cdfmoy.nc in case of -save option.
+            variables :  IN-var, same units than input variables.
+       
+      SEE ALSO :
+         cdfmoy, cdfrmsssh, cdfstdevw</code></pre>
+
+<h2 id="cdfstdevts">cdfstdevts</h2>
+
+<pre><code>  usage : cdfstdevts T-file T2-file 
+       
+      PURPOSE :
+        Compute the standard deviation of the temperature
+        and salinity from their mean and  mean square values. 
+       
+      ARGUMENTS :
+        T-file  : netcdf file with mean values for T, S
+        T2-file : netcdf file with mean squared values for T,S
+       
+      REQUIRED FILES :
+        none
+       
+      OUTPUT : 
+        netcdf file : stdevts.nc
+          variables : votemper_stdev, same unit than the input.
+                      vosaline_stdev, same unit than the input.
+       
+      SEA ALSO :
+        cdfstd, cdfrmsssh, cdfstdevw.</code></pre>
+
+<h2 id="cdfstdevw">cdfstdevw</h2>
+
+<pre><code>  usage : cdfstdevw W-file W2-file [varname] [-o output_file] [-nc4 ]
+       
+      PURPOSE :
+        Computes the standard deviation of the vertical velocity
+        from its mean value and its mean square value. If a variable name 
+        is given, then computes rms of this variable instead of the vertical 
+        velocity.
+       
+        Note that what is computed in this program is stictly the
+        standard deviation. It is very often called RMS, which is
+        an abuse. It is the same only in the case of zero mean value.
+       
+      ARGUMENTS :
+        W-file  : netcdf file with mean values for w ( or given variable)
+        W2-file : netcdf file with mean squared values for w (or given variable)
+       
+      OPTIONS: 
+         varname : give name of variable if not vovecrtz
+       
+      REQUIRED FILES :
+        none
+       
+      OUTPUT : 
+        netcdf file : rmsw.nc (if varname specified, output file is rms_var.nc)
+          variables : vovecrtz_rms, (or varname_rms)  same unit than the input.
+       
+      SEA ALSO :
+        cdfstd, cdfrmsssh, cdfstdevts.</code></pre>
+
+<h2 id="cdfstrconv">cdfstrconv</h2>
+
+<pre><code>  Usage : cdfstrconv YEAR config 
+     Output 6 cdf files : for emp, qnet, qsr, sst, taux, tauy with standard var 
+ name :
+         sowaflup, sohefldo, soshfldo, sst, sozotaux, sometauy 
+     coordinates.diags ( clipper like) is required in current dir </code></pre>
+
+<h2 id="cdfsum">cdfsum</h2>
+
+<pre><code>  usage : cdfsum -f IN-file -v IN-var -p T| U | V | F | W  ... 
+           ... [-zoom imin imax jmin jmax kmin kmax] [-full ] [-o OUT-file] 
+           ... [-M MSK-file VAR-mask ]
+       
+      PURPOSE :
+        Computes the sum value of the field (3D, weighted)
+        This sum can be optionally limited to a 3D sub-area.
+       
+      ARGUMENTS :
+        -f IN-file : netcdf input file.
+        -v IN-var  : netcdf variable to work with.
+        -p T| U | V | F | W : C-grid point where IN-var is located.
+       
+      OPTIONS :
+        [-zoom imin imax jmin jmax kmin kmax] : limit of the 3D sub area. 
+               if imin=0 all i are taken
+               if jmin=0 all j are taken
+               if kmin=0 all k are taken
+        [ -full : ] Use full steps instead of default partial steps
+        [-o OUT-file ] : name of the output file instead ofcdfsum.nc
+        [-M MSK-file VAR-mask] : Allow the use of a non standard mask file 
+               with VAR-mask, instead of mask.nc and the variable
+               associated with the grid point set by -p argument.
+               This option is a usefull alternative to -zoom option, when the 
+               area of interest is not 'box-like' 
+       
+      REQUIRED FILES :
+       mesh_hgr.nc, mesh_zgr.nc and mask.nc. If
+          -M option is used, the specified mask file is required instead 
+          mask.nc
+       
+      OUTPUT : 
+        Standard output.
+        netcdf file : cdfsum.nc unless modified with -o option. 
+            - 2 variables : vertical profile of sum and 3D sum.
+                          names are sum_<varname> and sum3D_<varname>.
+       
+      SEE ALSO: 
+        cdfmean </code></pre>
+
+<h2 id="cdftempvol-full">cdftempvol-full</h2>
+
+<pre><code> Usage : cdftempvol-full  gridTfile  imin, imax, jmin, jmax temp_max temp_min nbins [options]
+            imin, imax, jmin, jmax : horizontal limit of the box
+            temp_max, temp_min : limit for temperature bining 
+                           nbins : number of bins to use 
+     Possible options :
+         -print :additional output is send to std output
+         -bimg : 2D (x=lat/lon, y=temp) output on bimg file for hiso, cumul trp, trp
+ Files mesh_hgr.nc, mesh_zgr.nc must be in the current directory
+ Output on voltemp.txt</code></pre>
+
+<h2 id="cdftransport">cdftransport</h2>
+
+<pre><code>  usage : cdftransport [-test  u v ] [-noheat ] [-plus_minus ] [-obc] [-TS] 
+                   ... [VT-file] U-file V-file [-full] |-time jt] ...
+                   ... [-time jt ] [-zlimit limits of level] [-self]
+       
+     PURPOSE :
+       Compute the transports accross a section.
+       The name of the section and the imin, imax, jmin, jmax for the section 
+       is read from the standard input. To finish the program use the key name
+       'EOF' for the section name.
+       OBC U,V files can be used if -obc option is specified.
+       
+      ARGUMENTS :
+       [VT-file ] : netcdf file with mean values of vt, vs, ut, us for heat and
+                    salt transport. If options -noheat or -plus_minus are used
+                    this file name must be omitted.
+       [U-file ] : netcdf file with the zonal velocity component.
+       [V-file ] : netcdf file with the meridional velocity component.
+       
+      OPTIONS :
+       [-test u v ]: use constant the u and v velocity components for sign 
+                     test purpose.
+       [-noheat ]  : use when heat and salt transport are not requested.
+                     This option must come before the file names, and if used
+                     VT file must not be given.
+       [ -plus_minus or -pm ] : separate positive and negative contribution to
+                     the volume transport. This option implicitly set -noheat,
+                     and must be used before the file names.
+       [-obc ]    : indicates that input files are obc files (vertical slices)
+                    Take care that for this case, mesh files must be adapted.
+                    This option implicitly set -noheat, and must be used before
+                    the file names.
+       [ -TS ]    : Indicate that UT VT US VS will be recomputed from T U V 
+                    files. T-file is passed as the first file instead of VT 
+       [-full ]   :  use for full step configurations.
+       [-time jt ]:  compute transports for time index jt. Default is 1.
+       [-zlimit list of depth] : Specify depths limits defining layers where the
+                     transports will be computed. If not used, the transports 
+                     are computed for the whole water column. If used, this 
+                     option must be the last on the command line.
+       [ -self ] : This option indicates that input files corresponds to a 
+                   broken line, hence  data files hold the metrics.
+       
+      REQUIRED FILES :
+       Files mesh_hgr.nc, mesh_zgr.nc must be in the current directory.
+             unless -self option is used.
+       
+      OUTPUT : 
+       - Standard output 
+       - ASCII file reflecting the standard output: section_trp.dat
+       - ASCII files for volume, heat and salt transport: vtrp.txt, htrp.txt 
+           and strp.txt.
+       - Netcdf files for each section. name of the file is buildt
+           from section name.
+       
+      SEE ALSO :
+        cdfsigtrp cdf_xtrac_brokenline
+       </code></pre>
+
+<h2 id="cdfuv">cdfuv</h2>
+
+<pre><code>  usage : cdfuv CONFIG-CASE 'list_of_tags' 
+      PURPOSE :
+        Compute the time average values for U.V  product, at T point.
+        Mean U and V values at T points, and mean U'.V' product are 
+        saved as well.
+       
+      ARGUMENTS :
+        CONFIG-CASE is the config name of a given experiment (eg ORCA025-G70)
+             The program will look for gridU and gridV files for
+             this config (grid_U and grid_V are also accepted).
+        list_of_tags : a list of time tags that will be used for time
+             averaging. e.g. y2000m01d05 y2000m01d10 ...
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        netcdf file : uv.nc
+        variables : vouv  : Mean U.V at T point
+                    vozocrtx_t : Mean U at T point
+                    vomecrty_t : Mean V at T point
+                    vouv_prime : Mean U'.V' at T point</code></pre>
+
+<h2 id="cdfvFWov">cdfvFWov</h2>
+
+<pre><code>  usage : cdfvFWov V-secfile S-secfile ZGR-secfile HGR-secfile MSK-secfile
+      PURPOSE :
+         Compute the fresh water transport and its overturning component through
+         a section specified by the input files (data and metrics).
+       
+      ARGUMENTS :
+         All arguments are 'section files', which are assumed to be files with
+         2 zonal lines of data ( j and j+1 ): 
+          - V_secfile : meridional velocity section file.
+          - S_secfile : salinity section file.
+          - ZGR_secfile : mesh_zgr section file 
+          - HGR_secfile : mesh_hgr section file 
+          - MSK_secfile : mask section file 
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        netcdf file : vFWov.nc
+        variables : netvFW, totvFW, ovFW
+        Output file only has time relevant dimension. Other dims are set to 1.
+        Degenerated dimensions can be removed with :
+            ncwga -a x,y,depthw vFWov.nc -o out.nc</code></pre>
+
+<h2 id="cdfvT">cdfvT</h2>
+
+<pre><code>  usage : cdfvT CONFIG-CASE [-o output_file ] [-nc4 ] 'list_of_tags' 
+      PURPOSE :
+        Compute the time average values for second order products 
+        V.T, V.S, U.T and U.S used in heat and salt transport computation.
+       
+      ARGUMENTS :
+        CONFIG-CASE is the config name of a given experiment (eg ORCA025-G70)
+             The program will look for gridT, gridU and gridV files for
+             this config ( grid_T, grid_U and grid_V are also accepted).
+             Additionaly, if gridS or grid_S file is found, it will be taken
+             in place of gridT for the salinity variable.
+        [-nc4 ] use netcdf4 output with chunking and deflation 1
+        [-o output file ] default :vt.nc  must be before tag list
+        list_of_tags : a list of time tags that will be used for time
+             averaging. e.g. y2000m01d05 y2000m01d10 ...
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        netcdf file : vt.nc
+        variables : vozout, vozous, vomevt and vomevs</code></pre>
+
+<h2 id="cdfvar">cdfvar</h2>
+
+<pre><code>  usage : cdfbathy/cdfvar -f IN-file [options]
+       
+      PURPOSE :
+        Allow manual modification of the input file. Very convenient
+        for bathymetric files, can also be used with any model file
+        Keep a log.f90 file of the modifications for automatic reprocessing
+       
+      ARGUMENTS :
+        IN-file : original input file. The program works on a copy of the
+                 original file (default)
+       
+      OPTIONS :
+        -file (or -f )       : name of input file 
+        -var  (or -v )       : name of cdf variable [default: Bathymetry]
+        -lev  (or -l )       : level to work with 
+        -time (or -t )       : time to work with 
+        -scale  s            : use s as a scale factor (divide when read the file)
+        -zoom (or -z )       : sub area of the bathy file to work with (imin imax jmin jmax)
+        -fillzone (or -fz )  : sub area will be filled with 0 up to the first coast line 
+        -fillpool (or -fp ) [ icrit ] : the whole file is check and fill all the pool smaller than (icrit) cell by 0
+        -raz_zone (or -raz ) : sub area will be filled with 0 up 
+        -raz_below depmin    : any depth less than depmin in subarea will be replaced by 0 
+           (or -rb depmin )  
+        -set_below depmin    : any depth less than depmin in subarea will be replaced by depmin 
+           (or -sb depmin ) 
+        -fullstep depmin     : sub area will be reshaped as full-step, below depmin
+           (or -fs depmin )    requires the presence of the file zgr_bat.txt (from ocean.output, eg )
+        -dumpzone (or -d )   : sub area will be output to an ascii file, which can be used by -replace
+                               after manual editing 
+        -nicedumpzone        : sub area will be output to an ascii file (nice output)
+                 (or -nd )
+        -replace (or -r )    : sub area defined by the file will replace the original bathy
+        -append (or -a )     : fortran log file (log.f90) will be append with actual modif
+                               Standard behaviour is to overwrite/create log file
+        -overwrite (or -o )  : input bathy file will be used as output.
+                               Standard behaviour is to use a work copy of the original file
+                               (indexed from 01 to 99 if necessary ) 
+        -log logfile         : log file for change (default is log.f90) 
+       
+      OUTPUT : 
+           netcdf file : according to used options, if the original file is to be modified
+                  a sequence number is added at the end of the input file name, to keep
+                  modifications.
+             variables : same as input file</code></pre>
+
+<h2 id="cdfvertmean">cdfvertmean</h2>
+
+<pre><code>  usage :  cdfvertmean [-debug] IN-file IN-var1,var2,.. v-type dep1 dep2 [-full]
+               ... [-o OUT-file ]
+       
+      PURPOSE :
+        Compute the vertical mean between dep1 and dep2 given in m,
+        for variable IN-var in the input file.
+       
+      ARGUMENTS :
+        IN-file  : netcdf input file.
+        IN-var1,var2,.. : Comma separated list of input variables to process.
+        v-type   : one of T U V W indicating position of variable on C-grid
+        dep1 dep2 : depths limit for vertical integration (meters), from top 
+                 to bottom, positive depths.
+       
+      OPTIONS :
+        [-full  ] : for full step configurations. Default is partial step.
+        [-debug ] : print some extra informations.
+        [-o OUT-file ] : specify output file instead of vertmean.nc
+       
+      REQUIRED FILES :
+        mesh_zgr.nc and mask.nc
+       
+      OUTPUT : 
+        netcdf file : vertmean.nc
+          variables : varin_vertmean (same units as input variable)
+       </code></pre>
+
+<h2 id="cdfvhst">cdfvhst</h2>
+
+<pre><code>  usage : cdfvhst  VTfile [-full ]
+      PURPOSE :
+          Computes the vertically integrated heat and salt transports 
+          at each grid cell.
+       
+      ARGUMENTS :
+          VTfile : file which contains UT, VT, US, VS quantities
+               (produced by cdfvT.f90)
+       
+      OPTIONS :
+          [ -full ] : use full step computation (default is partial steps).
+       
+      REQUIRED FILES :
+          Files mesh_hgr.nc, mesh_zgr.nc
+       
+      OUTPUT : 
+          Netcdf file : trp.nc
+          Variables : somevt, somevs, sozout and  sozous</code></pre>
+
+<h2 id="cdfvint">cdfvint</h2>
+
+<pre><code>  usage : cdfvint T-file [IN-var] [-GSOP] [-OCCI] [-full] [-nc4] [-o OUT-file]
+                  [-tmean] [-smean]
+       
+      PURPOSE :
+           Compute the vertical integral of the variable from top 
+        to bottom, and save the cumulated valued, level by level.
+        For temperature (default var), the integral is transformed
+        to Heat Content ( 10^6 J/m2) hence for salinity, the integral
+        represents PSU.m 
+       
+      ARGUMENTS :
+          T-file : gridT file holding either temperature or salinity 
+         [IN-var ] : name of input variable to process. Default is 
+                votemper. Can also be vosaline
+       
+      OPTIONS :
+         -GSOP : Use 7 GSOP standard level for the output 
+                 Default is to take the model levels for the output
+         -OCCI : Use 3 levels for the output: 700m, 2000m and bottom
+                 Default is to take the model levels for the output
+         -full : for full step computation 
+         -nc4  : use netcdf4 output with chunking and deflation
+         -tmean : output mean temperature instead of heat content
+         -smean : output mean salinity instead of PSU.m
+         -o OUT-file : use specified output file instead of <IN-var>.nc
+       
+      REQUIRED FILES :
+        mask.nc, mesh_hgr.nc and mesh_zgr.nc
+       
+      OUTPUT : 
+        netcdf file :  VAR-name.nc (or specified with -o option)
+          variables :  either voheatc or vohsalt, unless -tmean or -smean used
+                In this latter case, variables are votemper and 
+               vosaline
+       
+      SEE ALSO :
+         cdfvertmean, cdfheatc, cdfmxlhcsc and  cdfmxlheatc
+       </code></pre>
+
+<h2 id="cdfvita">cdfvita</h2>
+
+<pre><code>  usage : cdfvita U-file V_file T-file [-w W-file] [-geo ] [-cubic] [-nc4] ...
+                  ... [-o OUT-file] [-lev level_list]
+       
+      PURPOSE :
+        Create a file with velocity components, module  and direction
+        at T points from file on C-grid. T-file is used only for
+        getting the header of the output file. Any file on T grid
+        can be used.
+       
+      ARGUMENTS :
+        U-file  : netcdf file with zonal component of velocity
+        V-file  : netcdf file with meridional component of velocity
+        T-file  : netcdf file with T points header OK.
+       
+      OPTIONS :
+        [ -w W-file ] : if used, also compute vertical velocities at
+                        T points.
+        [ -geo ]     : indicate that input velocity files are produced 
+                       by cdfgeo-uv, hence ugeo on V-point, vgeo on U-points
+                       ( U-file and V_file are the same !)
+        [ -cubic ]   : Save the cube of the veocity module 
+        [ -nc4 ]     : Use netcdf4 output with chunking and deflation level 1
+                  This option is effective only if cdftools are compiled with
+                  a netcdf library supporting chunking and deflation.
+        [ -o OUT-file ] : Specify name of output file instead of vita.nc
+        [ -lev level_list] : specify a list of level to be used 
+                    (default option is to use all input levels).
+                    This option MUST be the last on the command line !!
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        netcdf file : vita.nc unless -o option is used
+          variables : sovitua, sovitva, sovitmod, sovitdir, [sovitmod3], [sovitw
+ a]</code></pre>
+
+<h2 id="cdfvita-geo">cdfvita-geo</h2>
+
+<pre><code>  usage : cdfvita-geo  Ugeo-file Vgeo_file T-file [-w W-file] [-lev level_list]
+       
+      PURPOSE :
+        Create a file with velocity components and module computed
+        at T points from file on C-grid. T-file is used only for
+        getting the header of the output file. Any file on T grid
+        can be used.
+       
+      ARGUMENTS :
+        Ugeo-file  : netcdf file with zonal component of velocity
+        Vgeo-file  : netcdf file with meridional component of velocity
+        T-file  : netcdf file with T points header OK.
+       
+      OPTIONS :
+        [ -w W-file ] : if used, also compute vertical velocities at
+                        T points.
+        [ -lev level_list] : specify a list of level to be used 
+                    (default option is to use all input levels).
+                    This option MUST be the last on the command line !!
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        netcdf file : vita.nc
+          variables : sovitua, sovitva, sovitmod, [sovitwa]</code></pre>
+
+<h2 id="cdfvsig">cdfvsig</h2>
+
+<pre><code>  usage : cdfvsig CONFIG  [-no-w] [-no-sig]  [-no-uv] [-T ] [-pref pref1,pref2,.
+ ..]
+         ... 'list_of_tags' 
+      PURPOSE :
+        Compute the time average values for second order products 
+        U.sig,  V.sig and W.sig.  Also save mean sigma-0 interpolated at
+        velocity points, as well as mean velocity component, for further use.
+       
+      ARGUMENTS :
+        CONFIG is the config name of a given experiment (eg ORCA025-G70)
+             The program will look for gridT, gridU, gridV  and gridW files for
+             this config ( grid_T, grid_U, grid_V and grid_W are also accepted).
+        list_of_tags : a list of time tags that will be used for time
+             averaging. e.g. y2000m01d05 y2000m01d10.
+             ! IMPORTANT : list_of_tag are at the end of the command line ! 
+       
+      OPTIONS ( to be used before the list_of tags ):
+         -T : compute u and v at T points, so that usig, vsig will be at T point
+         -no-w : no computation of vertical products
+         -no-sig : no output of density on U V points
+         -no-uv : no output of mean velocity components
+         -pref pref1,pref2,..: give comma separated list of reference depths for
+              density computation. eg : -pref 0,2000,3000  If not specified 
+              assumes pref=0.
+       
+      REQUIRED FILES :
+         mask.nc
+       
+      OUTPUT : 
+        netcdf file : usig.nc, vsig.nc and wsig.nc
+        variables : vousig, vovsig, vowsig : mean product v x sigma-0 
+                                             at velocity point.
+                    vosigu, vosigv, vosigw : mean sigma-0 at velocity point.
+                    vozocrtx, vomecrty, vovecrtz : mean velocity components.</code></pre>
+
+<h2 id="cdfvtrp">cdfvtrp</h2>
+
+<pre><code>  usage : cdfvtrp  U-file V-file [ -full ] [ -bathy ]
+      PURPOSE :
+        Computes the vertically integrated transports at each grid cell.
+       
+      ARGUMENTS :
+        U-file : netcdf gridU file
+        V-file : netcdf gridV file
+       
+      REQUIRED FILES :
+         mesh_hgr.nc and mesh_zgr.nc
+         mask.nc is required only with -bathy option.
+       
+      OPTIONS :
+        [-full ]  : To be used in case of full step configuration.
+                    Default is partial steps.
+        [-bathy ] : When used, cdfvtrp also compute the along slope
+                    and cross slope transport components.
+                    Bathymetry is read from mesh_zgr.nc file.
+       
+      OUTPUT : 
+        netcdf file : trp.nc
+        variables : 
+            sozoutrp : zonal transport.
+            somevtrp : meridional transport.
+           If option -bathy is used :
+            soastrp : along slope transport
+            socstrp : cross slope transport</code></pre>
+
+<h2 id="cdfw">cdfw</h2>
+
+<pre><code>  usage : cdfw U-file V-file [ U-var V-var ] [ -full]
+       
+      PURPOSE :
+        Compute the vertical velocity from the vertical integration of
+        of the horizontal divergence of the velocity.
+       
+      ARGUMENTS :
+        U-file : netcdf file with the zonal velocity component.
+        V-file : netcdf file with the meridional velocity component.
+       
+      OPTIONS :
+        [ U-var V-var ] : names of the zonal and meridional velocity 
+                          components. Default are vozocrtx and vomecrty
+        [ -full ] : in case of full step configuration. Default is partial step.
+       
+      REQUIRED FILES :
+        mesh_hgr.nc and mesh_zgr.nc
+       
+      OUTPUT : 
+        netcdf file : w.nc
+          variables : vovecrtz (m/s)</code></pre>
+
+<h2 id="cdfweight">cdfweight</h2>
+
+<pre><code>  usage : cdfweight  [-f] IN-file [-c COORD-file] ... 
+               ...  [-t point_type] [-2d] [-v] 
+       
+      PURPOSE :
+        Produce a weight file for further bilinear collocalisation 
+        with cdfcoloc program. It takes the position of the points
+        to be collocated into a simple ascii file. 
+       
+      ARGUMENTS :
+        [-f ] IN-file   : input file is a iyxz ASCII file, 1 line per point.
+       
+      OPTIONS :
+        [-c COORD-file] : coordinate file [coordinates.nc]
+        [-t point_type] : point type on C-grid (either T U V or F ) [F]
+        [-2d ]          : tell cdfweight that only 2D weights are to be computed
+ .
+        [-v ]           : Verbose mode for extra information (debug mode).
+       
+      REQUIRED FILES :
+         coordinates.nc file if not passed as argument.
+         If working with 3D files, mesh_zgr.nc is required.
+       
+      OUTPUT : 
+        binary weight file : weight_point_type.bin
+        standard output : almost the same info that is saved in the binary file
+                    When using -v option, even more informations !</code></pre>
+
+<h2 id="cdfwflx">cdfwflx</h2>
+
+<pre><code>  usage : cdfwflx T-file Runoff
+       
+      PURPOSE :
+        Computes the water fluxes components. Suitable for 
+        annual means files. All output variables are in mm/days.
+       
+      ARGUMENTS :
+        T-file  : model output file with water fluxes (gridT) 
+        Runoff : file with the climatological runoff on the
+                 model grid.
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        netcdf file : wflx.nc
+        variables : soevap, soprecip, sorunoff, sowadmp, sowaflux</code></pre>
+
+<h2 id="cdfwhereij">cdfwhereij</h2>
+
+<pre><code>  usage : cdfwhereij  imin imax jmin jmax [-c COOR-file ] [ -p point_type]
+       
+      PURPOSE :
+        Return the geographical coordinates of a model sub-area specified
+        in i,j space on the command line.
+       
+      ARGUMENTS :
+        imin imax jmin jmax : (i,j) space window coordinates
+       
+      OPTIONS :
+        [-c COOR_file  ] : specify a coordinates file.
+                       default is coordinates.nc
+        [-p point type ] : specify a point type on the C-grid (T U V F) 
+                       default is T
+       
+      REQUIRED FILES :
+        coordinates.nc or COOR-file given in the -c option
+       
+      OUTPUT : 
+        Standard output</code></pre>
+
+<h2 id="cdfzisot">cdfzisot</h2>
+
+<pre><code>  usage : cdfzisot T-file RefTemp [Output File]
+       
+      PURPOSE :
+        Compute depth of an isotherm given as argument
+       
+      ARGUMENTS :
+        T-file  : input netcdf file (gridT)
+        RefTemp : Temperature of the isotherm.
+        Output File : netCDF Optional (defaults: zisot.nc)
+       
+      REQUIRED FILES :
+         mesh_zgr.nc
+          In case of FULL STEP configuration, bathy_level.nc is also required.
+       
+      OUTPUT : 
+        netcdf file : zisot.nc</code></pre>
+
+<h2 id="cdfzonalmean">cdfzonalmean</h2>
+
+<pre><code>  usage : cdfzonalmean IN-file point_type [ BASIN-file] [-debug]...
+        ...[-var var1,var2,..] [-max ] [-pdep | --positive_depths]
+       
+      PURPOSE :
+        Compute the zonal mean of all the variables available in the
+        input file. This program assume that all the variables are
+        located on the same C-grid point, specified on the command line.
+          Using -var option limits the variables to be processed.
+       
+        Zonal mean is in fact the mean value computed along the I coordinate.
+        The result is a vertical slice, in the meridional direction.
+       
+        REMARK : partial step are not handled properly (but probably 
+                 minor impact on results).
+       
+      ARGUMENTS :
+        IN-file    : input netcdf file.
+        point_type : indicate the location on C-grid (T|U|V|F|W)
+       
+      OPTIONS :
+        [BASIN-file] : netcdf file describing sub basins, similar to 
+                       new_maskglo.nc. If this name is not given 
+                       as option, only the global zonal mean is computed.
+        [-max     ] : output the zonal maximum and minimum of the variable 
+        [-var var1,var2,.. ] : Comma separated list of selected variables
+        [-pdep | --positive_depths ] : use positive depths in the output file.
+                       Default behaviour is to have negative depths.
+        [-ndep_in ] : negative depths are used in the input file.
+                       Default behaviour is to have positive depths.
+        [-debug   ] : add some print for debug
+       
+      REQUIRED FILES :
+        mesh_hgr.nc, mesh_zgr.nc and mask.nc
+       
+      OUTPUT : 
+        netcdf file : zonalmean.nc
+          variables : output variable names are built with the following
+                      convention: zoxxxx_bas
+                       where zo replace vo/so prefix of the input variable
+                       where bas is a suffix for each sub-basins (or glo)
+                       if a BASIN-file is used.
+                  If option -max is used, each standard output variable
+                      is associated with a var_max variable.</code></pre>
+
+<h2 id="cdfzonalmeanvT">cdfzonalmeanvT</h2>
+
+<pre><code>  usage : cdfzonalmeanvT [-b BASIN-file] [-pdep |--positive_depths] ... 
+                    ...  [-ndep_in]   CONFIG-CASE  'list_of_tags' 
+       
+      PURPOSE :
+        Compute the mean product of zonal mean V by zonal mean of T and S.
+       
+        Zonal mean is in fact the mean value computed along the I coordinate.
+        The result is a vertical slice, in the meridional direction.
+       
+        REMARK : partial step are not handled properly (but probably 
+                 minor impact on results).
+       
+      ARGUMENTS :
+        CONFIG-CASE is the config name of a given experiment (eg ORCA025-G70)
+             The program will look for gridT, gridU and gridV files for
+             this config ( grid_T, grid_U and grid_V are also accepted).
+             Additionaly, if gridS or grid_S file is found, it will be taken
+             in place of gridT for the salinity variable.
+        list_of_tags : a list of time tags that will be used for time
+             averaging. e.g. y2000m01d05 y2000m01d10 ...
+       
+      OPTIONS :
+        [-b BASIN-file] : netcdf file describing sub basins, similar to 
+                       new_maskglo.nc. If this name is not given 
+                       as option, only the global zonal mean is computed.
+        [-pdep | --positive_depths ] : use positive depths in the output file.
+                       Default behaviour is to have negative depths.
+        [-ndep_in ] : negative depths are used in the input file.
+                       Default behaviour is to have positive depths.
+        [-debug   ] : add some print for debug
+       
+      REQUIRED FILES :
+        mesh_hgr.nc, mesh_zgr.nc and mask.nc
+       
+      OUTPUT : 
+        netcdf file : zonalmeanvt.nc
+          variables : zovzot : mean product of zonal_mean(V) x zonal_mean(T)
+                      zovzot : mean product of zonal_mean(V) x zonal_mean(S)
+                        A suffix _bas is append to variable name oin order to
+                      indicate the basin (atl, inp, ind, pac) or glo for global
+          </code></pre>
+
+<h2 id="cdfzonalout">cdfzonalout</h2>
+
+<pre><code>  usage :  cdfzonalout ZONAL-file
+       
+      PURPOSE :
+         This is a formatting program for zonal files, either mean or integral.
+         It displays results on the standard output from the input zonal file.
+         It only works with 1D zonal variables, skipping 2D variables, that
+         cannot be easily displayed !
+       
+      ARGUMENTS :
+         ZONAL-file : input netcdf zonal file produced by one of the zonal
+                      tools.
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+         - Standard output,  structured in columns:
+              J  LAT  ( zonal mean, var = 1--> nvar) </code></pre>
+
+<h2 id="cdfzonalsum">cdfzonalsum</h2>
+
+<pre><code>  usage : cdfzonalsum IN-file point_type [ BASIN-file] ...
+                   ... [-var var1,var2,..] [-pdep | --positive_depths]
+                   ... [-pdeg | --per_degree] [-debug]
+       
+      PURPOSE :
+        Compute the zonal sum of all the variables available in the
+        input file. This program assume that all the variables are
+        located on the same C-grid point, specified on the command line.
+          Using -var option limits the variables to be processed.
+       
+        Zonal sum is in fact the integral value computed along the I coordinate.
+        The result is a vertical slice, in the meridional direction.
+       
+        REMARK : partial step are not handled properly (but probably 
+                 minor impact on results).
+       
+      ARGUMENTS :
+        IN-file    : input netcdf file.
+        point_type : indicate the location on C-grid (T|U|V|F|W)
+       
+      OPTIONS :
+        [BASIN-file] : netcdf file describing sub basins, similar to 
+                       new_maskglo.nc. If this name is not given 
+                       as option, only the global zonal integral is computed.
+        [-var var1,var2,.. ] : Comma separated list of selected variables
+        [-pdep | --positive_depths ] : use positive depths in the output file.
+                       Default behaviour is to have negative depths.
+        [-pdeg | --per_degree ] : When using this option, the zonal integral
+                       is normalized per degree of latitude. This was formally
+                       done with cdfzonalintdeg program, which is now merged
+                       in this one.
+                       Default behaviour is not to normalize.
+        [-debug ] : add some print for debug
+       
+      REQUIRED FILES :
+        mesh_hgr.nc, mesh_zgr.nc and mask.nc
+       
+      OUTPUT : 
+        netcdf file : zonalsum.nc or zonalintdeg.nc (-pdeg option)
+          variables : output variable names are built with the following
+                      convention: zoixxxx_bas
+                       where zoi replace vo/so prefix of the input variable
+                       where bas is a suffix for each sub-basins (or glo)
+                       if a BASIN-file is used.
+             Units are modified by adding '.m2' at the end. Can be improved !
+             In addition, '.degree-1' is append to unit with -pdeg option.</code></pre>
+
+<h2 id="cdfzoom">cdfzoom</h2>
+
+<pre><code>  usage : cdfzoom -f file -zoom imin imax jmin jmax  ...
+                ... -var cdfvar [-lev kmin kmax ] ...
+                ... [ -time tmin tmax ] [ -fact factor] 
+      PURPOSE :
+       Display the numerical values of a zoomed area. By
+       default, all times and levels are shown. If the zoomed
+       area is degenerated to a single line, then the vertical
+       slab is displayed.
+       
+      ARGUMENTS :
+        -f file : name of input file
+        -zoom imin imax jmin jmax : spatial window definition
+        -var cdfvar : cdf variable name to work with.
+       
+      OPTIONS :
+        [-lev kmin kmax ]  : vertical limits for display.
+        [-time tmin tmax ] : time limits for display.
+        [-fact factor ]    : use a scaling factor for display.
+                             Values are DIVIDED by factor
+       
+      REQUIRED FILES :
+         none
+       
+      OUTPUT : 
+        display on standard output
+ </code></pre>
+
+<h1 id="AUTHORS">AUTHORS</h1>
+
+<p>Project headed by Jean-Marc Molines, (IGE, Grenoble - France)</p>
+
+<p>Contributors (alphabetic order ) : C.Q. Akuetevi, M. Balmaseda, E. Behrens, F. Castruccio, M. Chekki, P. Colombo, J. Deshayes, N. Djath, N. Ducousso, C. Dufour, R. Dussin, N. Ferry, F. Hernandez, M. Juza, A. Lecointre, S. Leroux, G. Mainsant, P. Mathiot, A. Melet, X. Meunier, G. Moreau, N. Merino, W. Rath, J. Regidor, M. Scheinert, A.M. Treguier</p>
+
+<h1 id="LICENSE-AND-COPYRIGHT">LICENSE AND COPYRIGHT</h1>
+
+<p>Copyright (C) 1998-2016 IGE-MEOM (Jean-Marc.Molines at univ-grenoble-alpes.fr )</p>
+
+<p>This software is governed by the CeCILL license under French law and abiding by the rules of distribution of free software. You can use, modify and/ or redistribute the software under the terms of the CeCILL license as circulated by CEA, CNRS and INRIA at the following URL "http://www.cecill.info".</p>
+
+<p>As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license, users are provided only with a limited warranty and the software's author, the holder of the economic rights, and the successive licensors have only limited liability.</p>
+
+<p>In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or developing or reproducing the software by the user in light of its specific status of free software, that may mean that it is complicated to manipulate, and that also therefore means that it is reserved for developers and experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the software's suitability as regards th [...]
+
+<p>The fact that you are presently reading this means that you have had knowledge of the CeCILL license and that you accept its terms.</p>
+
+
+</body>
+
+</html>
+
+
diff --git a/License/CDFTOOLSCeCILL.txt b/License/CDFTOOLSCeCILL.txt
index 640455a..a9db2eb 100644
--- a/License/CDFTOOLSCeCILL.txt
+++ b/License/CDFTOOLSCeCILL.txt
@@ -1,10 +1,13 @@
 The following licence information concerns ONLY the CDFTOOLS package
 =======================================================================
 
-Copyright � LEGI-MEOM (Jean-Marc.Molines at legi.grenoble-inp.fr )
-Contributors : M. Balmaseda, E. Behrens, F. Castruccio,  J. Deshayes,
-N. Djath, C. Dufour, R. Dussin, N. Ferry, F. Hernandez, M. Juza,
-A. Lecointre, P. Mathiot, A. Melet, G. Moreau, A.M. Treguier
+Copyright  IGE-MEOM (Jean-Marc.Molines at univ-grenoble-alpes.fr )
+Contributors (alphabetic order ) : 
+C.Q. Akuetevi, M. Balmaseda, E. Behrens, F. Castruccio, M. Chekki, 
+P. Colombo, J. Deshayes, N. Djath, N. Ducousso, C. Dufour, R. Dussin, 
+N. Ferry, F. Hernandez, M. Juza, A. Lecointre, S. Leroux, G. Mainsant, 
+P. Mathiot, A. Melet, X. Meunier, G. Moreau, N. Merino, W. Rath, 
+J. Regidor, M. Scheinert, A.M. Treguier
 
 This software is a computer program for analysis of NEMO model output 
 produced in the frame of the DRAKKAR project. It is designed  for the
diff --git a/Macrolib/macro.ada b/Macrolib/macro.ada
index 7d9d883..6cde95d 100644
--- a/Macrolib/macro.ada
+++ b/Macrolib/macro.ada
@@ -13,7 +13,12 @@ MPF90=mpiifort
 # flag static is used to allow the use of CDFTOOLS in parallel with mpi_metamon
 #FFLAGS= -O   -assume byterecl -convert big_endian -CB -fpe0 -g -traceback -ftrapuv
 
-FFLAGS= -O2 -assume byterecl -convert big_endian 
+#FFLAGS= -O2 -assume byterecl -convert big_endian 
+FFLAGS= -O2 -assume byterecl -convert big_endian -fpe0 -CB -ftrapuv -traceback -g -fp-model precise -fp-model source
+#FFLAGS=-O2 -xSSE4.1 -ip -ftz -fpe3 -fno-alias -sox -assume byterecl -convert big_endian -fp-model precise -fp-model source
+
+#OMP = -openmp
+OMP = 
 
 INSTALL=$(WORKDIR)/bin
 INSTALL_MAN=$(WORKDIR)/man
diff --git a/Macrolib/macro.curie b/Macrolib/macro.curie
index 9c7273e..79063f9 100644
--- a/Macrolib/macro.curie
+++ b/Macrolib/macro.curie
@@ -4,13 +4,21 @@
 #  $Id: macro.jade 539 2011-07-11 10:33:35Z molines $
 # -------------------------------------------------------------
 #
-NCDF= -I/usr/local/netcdf-4.1.1/include -L/usr/local/netcdf-4.1.1/lib -lnetcdff -lnetcdf
+#NCDF=-I/usr/local/netcdf-4.2_hdf5_parallel/include  -L/usr/local/netcdf-4.2_hdf5_parallel/lib -lnetcdff -lnetcdf -L/usr/local/hdf5-1.8.9_parallel/lib -lhdf5_hl -lhdf5 -lhdf5
+NCDF = -I$(NETCDF_INCDIR) $(NETCDF_LDFLAGS) -lnetcdff 
+
+#NC4 =
+NC4 = -D key_netcdf4  # define this key in order to compile cdftools with netcdf4 lib allowing for chunking and deflation
+
  
 F90=ifort
 MPF90=mpif90
 # flag static is used to allow the use of CDFTOOLS in parallel with mpi_metamon
 #FFLAGS= -static -O  $(NCDF) -assume byterecl -convert big_endian
-FFLAGS= -O  $(NCDF) -assume byterecl -convert big_endian
+#FFLAGS= -O  $(NCDF) -fpe0 -traceback -ftrapuv -g -CB  $(NC4) -fp-model precise
+#FFLAGS= -O  $(NCDF) -fpe0 -traceback -ftrapuv -g   $(NC4) -fp-model precise
+FFLAGS= -O2  $(NCDF)  $(NC4) -fp-model precise
+#FFLAGS= -O  $(NCDF) -assume byterecl -convert big_endian $(NC4)
 LMPI=-lmpich
 
 INSTALL=$(WORKDIR)/bin
diff --git a/Macrolib/macro.ftn_hlrn_nc4 b/Macrolib/macro.ftn_hlrn_nc4
new file mode 100755
index 0000000..d6c0f0b
--- /dev/null
+++ b/Macrolib/macro.ftn_hlrn_nc4
@@ -0,0 +1,11 @@
+# module load cray-netcdf cray-hdf5 
+
+LIBS = -L/sw/dataformats/szip/2.1/smp1/intel/lib/ -lhdf5 -lhdf5_fortran -lnetcdf -lnetcdff -lhdf5_hl -lhdf5hl_fortran -lz
+NC4 = -D key_netcdf4
+
+F90=ftn -e F # force preprocessor irrespective of capitalization of file name
+             # extension
+FFLAGS= $(NC4) -O 2  $(NCDF) $(LIBS)
+LMPI=-lmpich
+
+INSTALL=$(HOME)/local/bin/
\ No newline at end of file
diff --git a/Macrolib/macro.gforhp b/Macrolib/macro.gforhp
new file mode 100644
index 0000000..11e7e70
--- /dev/null
+++ b/Macrolib/macro.gforhp
@@ -0,0 +1,18 @@
+# Makefile for CDFTOOLS
+#    $Rev: 522 $
+#    $Date: 2011-06-17 12:50:13 +0200 (Fri, 17 Jun 2011) $
+# --------------------------------------------------------------
+#
+NCDF = -I/usr/include -L/usr/lib -lnetcdf -lnetcdff -lhdf5 -lhdf5_hl
+#NCDF = -I/opt/netcdf/4.2-gcc/include -lnetcdff -lnetcdf
+#NC4=
+NC4=-D key_netcdf4
+
+#F90=gfortran -v
+F90=gfortran 
+MPF90=
+#FFLAGS= -O  $(NCDF)  $(NC4) -fno-second-underscore -ffree-line-length-256
+FFLAGS= -O  -fcheck=bounds -g -fbacktrace -ffpe-trap='invalid','zero','overflow'  $(NCDF)  $(NC4) -fno-second-underscore -ffree-line-length-256
+LMPI=-lmpich
+
+INSTALL=$(HOME)/bin
diff --git a/Macrolib/macro.gfortran b/Macrolib/macro.gfortran
index 59f8561..6632146 100644
--- a/Macrolib/macro.gfortran
+++ b/Macrolib/macro.gfortran
@@ -3,8 +3,12 @@
 #    $Date: 2011-06-17 12:50:13 +0200 (Fri, 17 Jun 2011) $
 # --------------------------------------------------------------
 #
-#NCDF = -I/usr/local/include -L/usr/local/lib -lnetcdf
-NCDF = -I/usr/include -lnetcdff -lnetcdf
+#NETCDF_ROOT=/opt/netcdf-4.1.1-gfortran
+NETCDF_ROOT=/usr
+NCDF = -I$(NETCDF_ROOT)/include -L$(NETCDF_ROOT)/lib -lnetcdff -lnetcdf
+
+NC4= -D key_netcdf4
+
 
 #F90=gfortran -v
 F90=gfortran 
diff --git a/Macrolib/macro.gfortran_hlrn b/Macrolib/macro.gfortran_hlrn
new file mode 100644
index 0000000..e476abc
--- /dev/null
+++ b/Macrolib/macro.gfortran_hlrn
@@ -0,0 +1,10 @@
+# module load gcc/4.9.1.hlrn netcdf/4.3.3.1 hdf5/1.8.14 
+
+INCS = $(NETCDF_INC) $(HDF5_INC)
+LIBS = $(NETCDF_F90_LIB) $(HDF5_F90_LIB)
+ 
+F90=gfortran
+
+FFLAGS= -O $(INCS) $(LIBS) -fno-second-underscore -ffree-line-length-256
+
+INSTALL=$(HOME)/local/bin
diff --git a/Macrolib/macro.gfortran_hlrn_nc4 b/Macrolib/macro.gfortran_hlrn_nc4
new file mode 100644
index 0000000..43573ea
--- /dev/null
+++ b/Macrolib/macro.gfortran_hlrn_nc4
@@ -0,0 +1,12 @@
+# module load gcc/4.9.1.hlrn netcdf/4.3.3.1 hdf5/1.8.14 
+
+INCS = $(NETCDF_INC) $(HDF5_INC)
+LIBS = $(NETCDF_F90_LIB) $(HDF5_F90_LIB)
+
+NC4 = -D key_netcdf4
+ 
+F90=gfortran
+
+FFLAGS= $(NC4) -O $(INCS) $(LIBS) -fno-second-underscore -ffree-line-length-256
+
+INSTALL=$(HOME)/local/bin
diff --git a/Macrolib/macro.ifort b/Macrolib/macro.hplaptop
similarity index 59%
copy from Macrolib/macro.ifort
copy to Macrolib/macro.hplaptop
index 2ce9422..5d274dc 100644
--- a/Macrolib/macro.ifort
+++ b/Macrolib/macro.hplaptop
@@ -1,16 +1,15 @@
 # Makefile for CDFTOOLS
-#    $Rev$
-#    $Date$
+#    $Rev: 673 $
+#    $Date: 2013-06-03 10:54:29 +0200 (Mon, 03 Jun 2013) $
 # --------------------------------------------------------------
 #
 #NCDF = -I/usr/local/include -L/usr/local/lib -lnetcdf
-NCDF = -I/usr/local/netcdf-3.6.1/ifort/include -L /usr/local/netcdf-3.6.1/ifort/lib/  \
-       -I/opt/netcdf/include -L /opt/netcdf/lib/  \
-       -I/usr/local/include -L/usr/local/lib -lnetcdf
+NCDF = -I/opt/netcdf/4.2-intel/include -L/opt/netcdf/4.2-intel/lib -lnetcdf -lnetcdff
  
 F90=ifort
 MPF90=mpif90
 FFLAGS= -O  $(NCDF) -assume byterecl -convert big_endian -CB -fpe0 -g -traceback -ftrapuv
+#FFLAGS= -O  $(NCDF) -assume byterecl -convert big_endian 
 LMPI=-lmpich
 
 INSTALL=$(HOME)/bin
diff --git a/Macrolib/macro.ifort b/Macrolib/macro.ifort
index 2ce9422..3f8cfc0 100644
--- a/Macrolib/macro.ifort
+++ b/Macrolib/macro.ifort
@@ -7,10 +7,15 @@
 NCDF = -I/usr/local/netcdf-3.6.1/ifort/include -L /usr/local/netcdf-3.6.1/ifort/lib/  \
        -I/opt/netcdf/include -L /opt/netcdf/lib/  \
        -I/usr/local/include -L/usr/local/lib -lnetcdf
+
+NCDF = -I/opt/netcdf-4.1/include -I /opt/hdf5-1.8.4/include -L /opt/hdf5-1.8.4/lib -L/opt/netcdf-4.1/lib -lnetcdf -lhdf5_hl -lhdf5 -lz
+
+NC4= -D key_netcdf4
  
 F90=ifort
 MPF90=mpif90
-FFLAGS= -O  $(NCDF) -assume byterecl -convert big_endian -CB -fpe0 -g -traceback -ftrapuv
+FFLAGS= -O  $(NCDF) $(NC4) -assume byterecl -convert big_endian -CB -fpe0 -g -traceback -ftrapuv
+#FFLAGS= -O  $(NCDF) -assume byterecl -convert big_endian 
 LMPI=-lmpich
 
 INSTALL=$(HOME)/bin
diff --git a/Macrolib/macro.ifort_hlrn_nc4 b/Macrolib/macro.ifort_hlrn_nc4
new file mode 100644
index 0000000..f2f433d
--- /dev/null
+++ b/Macrolib/macro.ifort_hlrn_nc4
@@ -0,0 +1,36 @@
+# Makefile for CDFTOOLS
+#    $Rev: 522 $
+#    $Date: 2011-06-17 12:50:13 +0200 (Fri, 17 Jun 2011) $
+# --------------------------------------------------------------
+#
+#  mscheinert at geomar.de 2015-11-04  Better use at HLRN for [hb]data"
+#
+# Currently Loaded Modulefiles:
+#  1) modules/3.2.10.3                      6) craype-sandybridge                   11) HLRNenv                              16) pmi/5.0.9-1.0000.10911.0.0.ari       21) alps/5.2.1-2.0502.9041.11.6.ari
+#  2) eswrap/1.1.0-1.020200.1231.0          7) cray-mpich/7.2.5                     12) intel/15.0.1.133                     17) dmapp/7.0.1-1.0502.9501.5.219.ari    22) rca/1.0.0-2.0502.53711.3.127.ari
+#  3) switch/1.0-1.0502.54233.2.96.ari      8) moab/generic                         13) cray-libsci/13.2.0                   18) gni-headers/3.0-1.0502.9684.5.2.ari  23) PrgEnv-intel/5.2.40
+#  4) craype-network-aries                  9) torque/generic                       14) udreg/2.3.2-1.0502.9275.1.12.ari     19) xpmem/0.1-2.0502.55507.3.2.ari       24) cray-netcdf/4.3.3.1
+#  5) craype/2.4.2                         10) sw.mpp1                              15) ugni/5.0-1.0502.9685.4.24.ari        20) dvs/2.5_0.9.0-1.0502.1873.1.145.ari  25) cray-hdf5/1.8.14
+#
+# i.e. In most cases on [hb]login node:
+#
+#  module sw PrgEnv-cray/5.2.82 PrgEnv-intel/5.2.40
+#  module sw craype-ivybridge craype-sandybridge
+#  module load cray-netcdf/4.3.3.1
+#  module load cray-hdf5/1.8.14
+
+
+
+#NCDF = -I/usr/local/include -L/usr/local/lib -lnetcdf
+#NCDF = -l netcdf -l netcdff
+NCDF =
+LIBS = -L/sw/dataformats/szip/2.1/smp1/intel/lib/ -lhdf5 -lhdf5_fortran -lnetcdf -lnetcdff -lhdf5_hl -lhdf5hl_fortran -lz
+
+#F90=gfortran -v
+F90=ftn
+MPF90=
+#FFLAGS= -O  $(NCDF)  -fno-second-underscore -ffree-line-length-256
+FFLAGS= -O3  -fpp $(NCDF) $(LIBS) -Dkey_netcdf4
+LMPI=-lmpich
+
+INSTALL=../../../bin/
diff --git a/Macrolib/macro.ifort_nesh_fe b/Macrolib/macro.ifort_nesh_fe
new file mode 100644
index 0000000..ef088b8
--- /dev/null
+++ b/Macrolib/macro.ifort_nesh_fe
@@ -0,0 +1,16 @@
+# Makefile for CDFTOOLS : nesh-fe.rz.uni-kiel.de
+#
+# $ module load intel netcdf_intel hfd5_intel
+#
+# (Linked dynamically!)
+
+INSTALL = $(HOME)/bin
+
+# libs
+LIBS = \
+  -L$(HDF5_DIR)/lib -L$(NETCDF_DIR)/lib -I$(NETCDF_DIR)/include \
+  -lhdf5 -lnetcdf -lnetcdff -lhdf5_hl \
+  -L/lib64 -limf -lm -lz 
+
+F90 = ifort
+FFLAGS = -O -assume byterecl -convert big_endian $(LIBS) 
diff --git a/Macrolib/macro.jade b/Macrolib/macro.jade
index 9abcd01..acbc6c9 100644
--- a/Macrolib/macro.jade
+++ b/Macrolib/macro.jade
@@ -5,15 +5,26 @@
 # -------------------------------------------------------------
 #
 NCDF= -I/opt/software/SGI/netcdf/4.0/include -L/opt/software/SGI/netcdf/4.0/lib -lnetcdff -lnetcdf
- 
+#NCDF= -I/opt/software/SGI/netcdf/4.1.3/include -L/opt/software/SGI/netcdf/4.1.3/lib -lnetcdff -lnetcdf
+#NCDF = -I/opt/software/SGI/netcdf/netcdf-4.2_hdf5_1.8.9/include -L/opt/software/SGI/netcdf/netcdf-4.2_hdf5_1.8.9/lib -lnetcdff -lnetcdf
+#HDF5 = -I/opt/software/SGI/hdf5/1.8.9/include -L/opt/software/SGI/hdf5/1.8.9/lib -lhdf5 -lhdf5_fortran
+#HDF5 = -I/opt/software/SGI/hdf5/1.8.9-intelmpi/lib/include -L/opt/software/SGI/hdf5/1.8.9-intelmpi/lib -lhdf5 -lhdf5_fortran
+
 F90=ifort
 MPF90=mpif90
 # flag static is used to allow the use of CDFTOOLS in parallel with mpi_metamon
 #FFLAGS= -O  $(NCDF) -assume byterecl -convert big_endian -CB -fpe0 -g -traceback -ftrapuv
 
-FFLAGS= -static -O  $(NCDF) -assume byterecl -convert big_endian
+FFLAGS= -static -O2  $(NCDF)  -assume byterecl -convert big_endian
+#FFLAGS= -O2 -xSSE4.1 -ip -ftz -fpe3 -fno-alias -sox $(NCDF)  -assume byterecl -convert big_endian 
 #FFLAGS= -static -O  $(NCDF) -assume byterecl -convert big_endian -g -traceback -fpe0 -ftrapuv -CB
+#FFLAGS= -O  $(NCDF) -assume byterecl -convert big_endian -g -traceback -fpe0 -ftrapuv -CB
+
+#OMP= -openmp
+OMP=
 LMPI=-lmpich
 
+#-O3 -xSSE4.1 -ip -ftz -fpe3 -fno-alias -sox
+
 INSTALL=$(WORKDIR)/bin
 INSTALL_MAN=$(WORKDIR)/man
diff --git a/Macrolib/macro.lgge b/Macrolib/macro.lgge
new file mode 100644
index 0000000..b023f26
--- /dev/null
+++ b/Macrolib/macro.lgge
@@ -0,0 +1,19 @@
+# Makefile for CDFTOOLS
+#    $Rev: 827 $
+#    $Date: 2015-05-26 17:02:02 +0200 (mar. 26 mai 2015) $
+# --------------------------------------------------------------
+#
+#NCDF = -I/usr/local/include -L/usr/local/lib -lnetcdf
+
+NCDF = -I/opt/netcdf-4.1/include -I /opt/hdf5-1.8.4/include -L /opt/hdf5-1.8.4/lib -L/opt/netcdf-4.1/lib -lnetcdf -lhdf5_hl -lhdf5 -lz
+
+NC4= -D key_netcdf4
+ 
+F90=ifort
+MPF90=mpif90
+FFLAGS= -O  $(NCDF) $(NC4) -assume byterecl -convert big_endian -CB -fpe0 -g -traceback -ftrapuv
+#FFLAGS= -O  $(NCDF) -assume byterecl -convert big_endian 
+LMPI=-lmpich
+
+INSTALL=$(HOME)/bin
+INSTALL_MAN=$(HOME)/man
diff --git a/Macrolib/macro.meolkerg b/Macrolib/macro.meolkerg
index f09d019..1f743a4 100644
--- a/Macrolib/macro.meolkerg
+++ b/Macrolib/macro.meolkerg
@@ -3,19 +3,24 @@
 #    $Date: 2008-03-17 11:42:21 +0100 (lun 17 mar 2008) $
 # --------------------------------------------------------------
 #
-NCDF = -I/opt/netcdf-4.1/include -L /opt/netcdf-4.1/lib/  \
-       -lnetcdf
+#NCDF = -I/opt/netcdf-4.1/include -L /opt/netcdf-4.1/lib/ -lnetcdf
 HDF5 = -I/opt/hdf5-1.8.4/include -L/opt/hdf5-1.8.4/lib -lhdf5_hl -lhdf5 
 ZLIB = -I/opt/zlib-1.2.3/include -L/opt/zlib-1.2.3/lib -lz
 
+NCDF = -I/opt/netcdf/4.2-intel/include -L /opt/netcdf/4.2-intel/lib/ -lnetcdf -lnetcdff
 #NCDF = -I/opt/netcdf-4.1.1-ifort/include -L /opt/netcdf-4.1.1-ifort/lib/  \
 #       -lnetcdf
 #HDF5 = 
 #ZLIB =
+#NC4 =
+NC4 = -Dkey_netcdf4
  
 F90=ifort
 MPF90=mpif90
-FFLAGS= -O   $(NCDF) $(HDF5) $(ZLIB)  -assume byterecl -convert big_endian 
+FFLAGS= -O   -fp-model precise $(NCDF) $(NC4)  $(HDF5) $(ZLIB)  -fp-model precise
+#FFLAGS= -O   -fpe0 -CB -traceback -g -ftrapuv -fp-model precise $(NCDF) $(NC4) $(HDF5) $(ZLIB)  -assume byterecl -convert big_endian 
+#FFLAGS= -O  -fpe0 -CB -traceback -g -ftrapuv  $(NCDF) $(NC4) $(HDF5) $(ZLIB)
+#FFLAGS= -O  -fpe0 -CB -traceback -g -ftrapuv  $(NCDF) $(NC4) -assume byterecl -convert big_endian 
 LMPI=-lmpich
 
 INSTALL=/usr/local/cdftools_3.0/bin
diff --git a/Macrolib/macro.curie b/Macrolib/macro.occigen
similarity index 54%
copy from Macrolib/macro.curie
copy to Macrolib/macro.occigen
index 9c7273e..6415858 100644
--- a/Macrolib/macro.curie
+++ b/Macrolib/macro.occigen
@@ -3,14 +3,21 @@
 #  $Date: 2011-07-11 12:33:35 +0200 (Mon, 11 Jul 2011) $
 #  $Id: macro.jade 539 2011-07-11 10:33:35Z molines $
 # -------------------------------------------------------------
-#
-NCDF= -I/usr/local/netcdf-4.1.1/include -L/usr/local/netcdf-4.1.1/lib -lnetcdff -lnetcdf
+
+#NCDF= -I/scratch/cnt0024/hmg2840/molines/include -L/scratch/cnt0024/hmg2840/molines/lib -lnetcdf -lnetcdff
+NCDF = -I$(NETCDF_INCDIR) -I$(NETCDFF_INCDIR) $(_NETCDF_LDFLAGS) $(NETCDFF_LDFLAGS)
+
+#NC4=
+NC4=-Dkey_netcdf4
  
 F90=ifort
 MPF90=mpif90
 # flag static is used to allow the use of CDFTOOLS in parallel with mpi_metamon
 #FFLAGS= -static -O  $(NCDF) -assume byterecl -convert big_endian
-FFLAGS= -O  $(NCDF) -assume byterecl -convert big_endian
+
+FFLAGS= -O  $(NCDF) $(NC4) -fp-model precise
+#FFLAGS= -O  $(NCDF) -assume byterecl -convert big_endian -CB -fpe0 -ftrapuv -traceback -g
+
 LMPI=-lmpich
 
 INSTALL=$(WORKDIR)/bin
diff --git a/Macrolib/macro.curie b/Macrolib/macro.occigen2
similarity index 62%
copy from Macrolib/macro.curie
copy to Macrolib/macro.occigen2
index 9c7273e..4ff218a 100644
--- a/Macrolib/macro.curie
+++ b/Macrolib/macro.occigen2
@@ -3,14 +3,20 @@
 #  $Date: 2011-07-11 12:33:35 +0200 (Mon, 11 Jul 2011) $
 #  $Id: macro.jade 539 2011-07-11 10:33:35Z molines $
 # -------------------------------------------------------------
-#
-NCDF= -I/usr/local/netcdf-4.1.1/include -L/usr/local/netcdf-4.1.1/lib -lnetcdff -lnetcdf
+
+NCDF = -I$(NETCDF_INCDIR) -I$(NETCDFF_INCDIR) $(NETCDF_LDFLAGS) $(NETCDFF_LDFLAGS)
+
+#NC4=
+NC4=-Dkey_netcdf4
  
 F90=ifort
 MPF90=mpif90
 # flag static is used to allow the use of CDFTOOLS in parallel with mpi_metamon
 #FFLAGS= -static -O  $(NCDF) -assume byterecl -convert big_endian
-FFLAGS= -O  $(NCDF) -assume byterecl -convert big_endian
+
+FFLAGS= -O  $(NCDF) $(NC4) -fp-model precise
+#FFLAGS= -O  $(NCDF) $(NC4) -assume byterecl -convert big_endian -CB -fpe0 -ftrapuv -traceback -g
+
 LMPI=-lmpich
 
 INSTALL=$(WORKDIR)/bin
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..f36b891
--- /dev/null
+++ b/README.md
@@ -0,0 +1,86 @@
+# CDFTOOLS
+  CDFTOOLS is a diagnostic package written in fortran 90 for the analysis of NEMO model output, initialized in  the frame of the DRAKKAR project (<https://www.drakkar-ocean.eu/>). It is now available on GitHub under the CeCILL license (<http://www.cecill.info/licences/Licence_CeCILL_V2-en.html>).
+
+  CDFTOOLS is an open source package and contributions from other group are welcomed. The Git workflow policy is still to be defined.
+
+## Using CDFTOOLS
+
+#### Cloning the git repository
+To retrieve a copy of the CDFTOOLS source code and create a working directory, run the following on the command line: 
+
+```> git clone https://github.com/meom-group/CDFTOOLS ```
+
+#### Compiling CDFTOOLS
+All the fortran source are in src/ subdirectory. In src/ there is a Makefile for compiling the sources. The compiler/machines related definitions are supposed to be collected in a `make.macro` file. Some examples of `make.macro` are given in the Macrolib directory and can be used as template for a new compiler or new machine. Then the good practice is to make a link 
+
+```> cd src/```
+
+```> ln -sf ../Macrolib/macro.MACHINE  make.macro```
+
+In the `make.macro` file, the PATH for the netcdf library is specified, as well as compiler name and used flags.  In order to activate netcdf4/HDF5 chunking and deflation ( available in some cdftools), you need to set: 
+
+```NC4=-Dkey_netcdf4 ```
+
+in the make.macro file, otherwise set
+
+```NC4= ```
+
+Then using `make` (or even `make -j n` if you can compile on n cores), you will have the cdftools programs executable available in the bin/ sub directory. The executable files are ignore by git.
+
+
+#### Running CDFTOOLS
+CDFTOOLS is a collection of programs. Every single program performs one or many computation(s) using a set of input files and output the results as a netcdf file, and eventually also gives some results on the standard output. 
+
+CDFTOOLS coding rules imply that a `usage message` is displayed when just running the tool without any arguments ( or with -h ). At the moment it is the only up to date documentation. 
+
+As CDFTOOLS is a collection of programs, a full diagnostic of model output can be performed writing a script using a sequence of tools. This is done for example in the Drakkar Monitoring Tools (DMONTOOLS, soon available on GitHub!).
+
+## Coding CDFTOOLS
+#### Coding rules
+##### Syntax
+The coding rules are the NEMO coding rules, strictly followed. The idea is that people familiar with NEMO are familiar with CDFTOOLS. In DEV_TOOLS/ some template fortran line are available for program, modules, routine or function headers. Also a template for the `usage message`.
+##### Run time behaviour
+Any `cdftool`, run without argument or with option -h, should display a short documentation (`usage message`), similar to a unix man page, describing the purpose of the tool, the syntax (arguments,  options, etc...) and giving details on the output files. For some tools, mesh or/and mask files are required to be present in the working directory, with respective name `mesh_hgr.nc`, `mesh_zgr.nc` or `mask.nc` (links are OK). The usage message should indicate the required files.
+
+Example:
+
+
+```>    cdfcurl```
+
+       usage : cdfcurl -u U-file U-var -v V-file V-var -l levlist [-T] [-8]...
+            ... [-surf] [-overf] [-nc4] [-o OUT-file ]
+       
+      PURPOSE :
+        Compute the curl of a vector field, at a specified level.
+        If level is specified as 0, assume that the input files are
+        forcing files, presumably on A-grid. In this latter case, the
+        vector field is interpolated on the C-grid. In any case, the
+        curl is computed on the F-point (unless -T option is used).
+       
+      ARGUMENTS :
+        -u U-file U-var : file and variable name for zonal component
+        -v V-file V-var : file and variable name for meridional component
+        -l levlist    : levels to be processed. If set to 0, assume forcing file
+                 in input. Example of recognized syntax :
+                   -l "1,10,30"  or -l "1-20" or even -l "1-3,10-20,30-"
+                   -l  1 . Note that -l "3-" set a levlist from 3 to the bottom
+                   
+      OPTIONS :
+        -T : compute curl at T point instead of default F-point
+        -8 : save in double precision instead of standard simple precision.
+        -surf : work with single level C-grid (not forcing)
+        -overf : store the ratio curl/f where f is the coriolis parameter
+        -nc4 : use netcdf4 output with chunking and deflation 1
+        -o OUT-file : specify output file name instead of curl.nc
+       
+      REQUIRED FILES :
+         mesh_hgr.nc
+       
+      OUTPUT : 
+        netcdf file : curl.nc
+          variables : socurl or socurlt (if -T option), units : s^-1
+             or socurloverf, no units (if -overf option)
+
+##### Improving/modifying existing tool
+ It is possible to improve (of course !) or modify any tools, but <u>one important law to respect</u> is that the modified tool should still be able to be used with previous syntax, in order to avoid breaking of existing scripts using CDFTOOLS. If for some reason, this is not possible, then a discussion must be done to reach to a common decision. Eventually, some old options must be documented as osbolete in the usage message, which means that they may be removed from a future release. 
+
diff --git a/bin/.gitignore b/bin/.gitignore
new file mode 100644
index 0000000..125e342
--- /dev/null
+++ b/bin/.gitignore
@@ -0,0 +1,2 @@
+*
+!.*
diff --git a/cdfbuoyflx.f90 b/cdfbuoyflx.f90
deleted file mode 100644
index e62bf5b..0000000
--- a/cdfbuoyflx.f90
+++ /dev/null
@@ -1,315 +0,0 @@
-PROGRAM cdfbuoyflx
-  !!======================================================================
-  !!                     ***  PROGRAM  cdfbuoyflx  ***
-  !!=====================================================================
-  !!  ** Purpose :  Produce a file with the water flux separated into 4 components:
-  !!                E (evap), P (precip), R (runoff), dmp (sssdmp).
-  !!                The total water flux is E -P -R + dmp. Units in this program
-  !!                are mm/days.  (Up to that it is the same than cdfwflx)
-  !!
-  !!                It also produces un the same file the component of the heat flux
-  !!                Latent Heat FLux, Sensible Heat flux, Long Wave HF, Short Wave HF,
-  !!                Net HF
-  !!
-  !!                Buoyancy fluxes are also computed, as a net value but also with the
-  !!                contribution of each term.
-  !!
-  !!  ** Method  : Evap is computed from the latent heat flux : evap=-qla/Lv
-  !!               Runoff is read from the climatological input file
-  !!               dmp is read from the file (sowafldp)
-  !!               Precip is then computed as the difference between the
-  !!               total water flux (sowaflup) and the E-R+dmp. In the high latitudes
-  !!               this precip includes the effect of snow (storage/melting). Therefore
-  !!               it may differ slightly from the input precip file.
-  !!
-  !!               Heat fluxes are directly copied from the gridT files, same name, same units
-  !!               We also add sst and SSS for convenience.
-  !!
-  !!               Buoyancy fluxes are also computed as :
-  !!                  BF = -1/rho (alpha x TF  - beta SF )
-  !!                       (TF = thermal part, SF = haline part )
-  !!                  TF = 1/(rho x Cp)* Q
-  !!                  SF = 1/(1-SSS) x (E-P) x SSS
-  !!
-  !! History : 2.1  : 01/2008  : J.M. Molines : Original code
-  !!           3.0  : 12/2010  : J.M. Molines : Doctor norm + Lic.
-  !!----------------------------------------------------------------------
-  USE cdfio
-  USE eos
-  USE modcdfnames
-  !!----------------------------------------------------------------------
-  !! CDFTOOLS_3.0 , MEOM 2011
-  !! $Id$
-  !! Copyright (c) 2010, J.-M. Molines
-  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
-  !!----------------------------------------------------------------------
-  IMPLICIT NONE
-
-  INTEGER(KIND=4), PARAMETER                :: jp_varout=25
-  INTEGER(KIND=4)                           :: ncout, ierr
-  INTEGER(KIND=4)                           :: jt                                ! dummy loop index
-  INTEGER(KIND=4)                           :: narg, iargc                       ! command line 
-  INTEGER(KIND=4)                           :: npiglo, npjglo, npt               ! size of the domain
-  INTEGER(KIND=4), DIMENSION(jp_varout)     :: ipk, id_varout  
-
-  ! Physical constants
-  REAL(KIND=4)                              :: Lv = 2.5e6                        ! latent HF <--> evap conversion
-  REAL(KIND=4)                              :: Cp = 4000.                        ! specific heat of water 
-
-  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim, zdep                         ! time counter, deptht
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zmask, zcoefq, zcoefw             ! work array
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zalbet, zbeta                     ! work array
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: evap, precip, runoff, wdmp, wnet  ! water flux components
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: wice, precip_runoff               ! water flux components
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: qlat, qsb, qlw, qsw, qnet         ! heat flux components
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: b_evap, b_precip, b_runoff        ! BF water flux components
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: b_wdmp, bw_net                    ! BF water flux components
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: b_qlat, b_qsb, b_qlw              ! BF heat flux components
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: b_qsw , bh_net                    ! BF heat flux components
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zsst, zsss, buoyancy_fl             ! Total buoyancy flux
-
-  CHARACTER(LEN=256)                        :: cf_tfil , cf_rnfil                ! input file gridT and runoff
-  CHARACTER(LEN=256)                        :: cf_out='buoyflx.nc'               ! output file
-
-  TYPE(variable), DIMENSION(jp_varout)      :: stypvar                           ! structure for attributes
-
-  LOGICAL                                   :: lchk
-  !!----------------------------------------------------------------------
-  CALL ReadCdfNames()
-
-  !!  Read command line and output usage message if not compliant.
-  narg= iargc()
-  IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfbuoyflx  T-file RNF-file'
-     PRINT *,'      '
-     PRINT *,'     PURPOSE :'
-     PRINT *,'       Compute (or read) the heat and water fluxes components.'
-     PRINT *,'       Compute (or read) the net heat and water fluxes.'
-     PRINT *,'       Compute the buoyancy heat and water fluxes components.'
-     PRINT *,'       Compute the net buoyancy fluxes.'
-     PRINT *,'       Save sss and sst.'
-     PRINT *,'      '
-     PRINT *,'     ARGUMENTS :'
-     PRINT *,'       T-file   : netcdf file with ' 
-     PRINT *,'       RNF-file : netcdf file with runoff ' 
-     PRINT *,'      '
-     PRINT *,'     REQUIRED FILES :'
-     PRINT *,'        none'
-     PRINT *,'      '
-     PRINT *,'     OUTPUT : '
-     PRINT *,'       netcdf file : ', TRIM(cf_out) 
-     PRINT *,'         variables :  25 variables (2D)'
-     PRINT *,'      '
-     PRINT *,'     SEE ALSO :'
-     PRINT *,'      '
-     PRINT *,'      '
-     STOP
-  ENDIF
-
-  CALL getarg (1, cf_tfil)
-  CALL getarg (2, cf_rnfil)
-
-  lchk =           chkfile (cf_tfil )
-  lchk = lchk .OR. chkfile (cf_rnfil)
-  IF (lchk ) STOP ! missing files
-
-  npiglo = getdim (cf_tfil,cn_x)
-  npjglo = getdim (cf_tfil,cn_y)
-  npt    = getdim (cf_tfil,cn_t)
-
-  ! prepare output variables
-  ALLOCATE (zdep(1), tim(npt) )
-  zdep(1) = 0.
-  ipk(:)  = 1  ! all variables ( output are 2D)
-  stypvar%conline_operation = 'N/A'
-  stypvar%caxis             = 'TYX'
-
-  ! 1--> 7 water fluxes                     ;   ! 8 --> 12    heat fluxes
-  stypvar(1)%cname= 'evap'                  ;  stypvar(8)%cname= 'latent'      
-  stypvar(2)%cname= 'precip'                ;  stypvar(9)%cname= 'sensible'      
-  stypvar(3)%cname= 'runoff'                ;  stypvar(10)%cname= 'longwave'      
-  stypvar(4)%cname= 'sssdmp'                ;  stypvar(11)%cname= 'solar'      
-  stypvar(5)%cname= 'watnet'                ;  stypvar(12)%cname= 'heatnet'      
-  stypvar(6)%cname= 'wice'            
-  stypvar(7)%cname= 'precip_runoff'  
-
-  stypvar(1:7)%cunits='mm/day'              ;  stypvar(8:12)%cunits='W/m2'      
-  stypvar(1:7)%rmissing_value=0.            ;  stypvar(8:12)%rmissing_value=0.      
-  stypvar(1:7)%valid_min= -100.             ;  stypvar(8:12)%valid_min= -500.      
-  stypvar(1:7)%valid_max= 100.              ;  stypvar(8:12)%valid_max= 500.      
-  stypvar(1)%clong_name='Evaporation'       ;  stypvar(8)%clong_name='Latent Heat flux'      
-  stypvar(2)%clong_name='Precipitation'     ;  stypvar(9)%clong_name='Sensible Heat flux'       
-  stypvar(3)%clong_name='Runoff'            ;  stypvar(10)%clong_name='Long Wave Heat flux'      
-  stypvar(4)%clong_name='SSS damping'       ;  stypvar(11)%clong_name='Short Wave Heat flux'
-  stypvar(5)%clong_name='Total water flux'  ;  stypvar(12)%clong_name='Net Heat Flux'      
-  stypvar(6)%clong_name='Ice congelation and melting'  
-  stypvar(7)%clong_name='Precip and runoff together' 
-
-  stypvar(1)%cshort_name='evap'             ;  stypvar(8)%cshort_name='latent'      
-  stypvar(2)%cshort_name='precip'           ;  stypvar(9)%cshort_name='sensible'      
-  stypvar(3)%cshort_name='runoff'           ;  stypvar(10)%cshort_name='longwave'      
-  stypvar(4)%cshort_name='sssdmp'           ;  stypvar(11)%cshort_name='solar'      
-  stypvar(5)%cshort_name='watnet'           ;  stypvar(12)%cshort_name='heatnet'       
-  stypvar(6)%cshort_name='wice'  
-  stypvar(7)%cshort_name='precip_runoff' 
-
-  ! 13--> 17  buoy water fluxes             ;   ! 18 --> 22    buoy heat fluxes
-  stypvar(13)%cname= 'evap_b'               ;  stypvar(18)%cname= 'latent_b'
-  stypvar(14)%cname= 'precip_b'             ;  stypvar(19)%cname= 'sensible_b'
-  stypvar(15)%cname= 'runoff_b'             ;  stypvar(20)%cname= 'longwave_b'
-  stypvar(16)%cname= 'sssdmp_b'             ;  stypvar(21)%cname= 'solar_b'
-  stypvar(17)%cname= 'watnet_b'             ;  stypvar(22)%cname= 'heatnet_b'
-
-  stypvar(13:17)%cunits='1e-6 kg/m2/s'      ;  stypvar(18:22)%cunits='1e-6 kg/m2/s'
-  stypvar(13:17)%rmissing_value=0.          ;  stypvar(18:22)%rmissing_value=0.
-  stypvar(13:17)%valid_min= -100.           ;  stypvar(18:22)%valid_min= -500.
-  stypvar(13:17)%valid_max= 100.            ;  stypvar(18:22)%valid_max= 500.
-
-  stypvar(13)%clong_name='buoy flx evap'    ;  stypvar(18)%clong_name='buoy Latent Heat flux'
-  stypvar(14)%clong_name='buoy flx precip'  ;  stypvar(19)%clong_name='buoy Sensible Heat flux'
-  stypvar(15)%clong_name='buoy flx runoff'  ;  stypvar(20)%clong_name='buoy Long Wave Heat flux'
-  stypvar(16)%clong_name='buoy flx damping' ;  stypvar(21)%clong_name='buoy Short Wave Heat flux'
-  stypvar(17)%clong_name='buoy haline flx'  ;  stypvar(22)%clong_name='buoy thermo Flux'
-
-  stypvar(13)%cshort_name='evap_b'          ;  stypvar(18)%cshort_name='latent_b'
-  stypvar(14)%cshort_name='precip_b'        ;  stypvar(19)%cshort_name='sensible_b'
-  stypvar(15)%cshort_name='runoff_b'        ;  stypvar(20)%cshort_name='longwave_b'
-  stypvar(16)%cshort_name='sssdmp_b'        ;  stypvar(21)%cshort_name='solar_b'
-  stypvar(17)%cshort_name='watnet_b'        ;  stypvar(22)%cshort_name='heatnet_b'
-
-  ! total buoyancy flux
-  stypvar(23)%cname= 'buoyancy_fl'
-  stypvar(23)%cunits='1e-6 kg/m2/s'
-  stypvar(23)%rmissing_value=0.
-  stypvar(23)%valid_min= -100.
-  stypvar(23)%valid_max= 100.
-  stypvar(23)%clong_name='buoyancy flux'
-  stypvar(23)%cshort_name='buoyancy_fl'
-
-  ! SSS                                         ; SST
-  stypvar(24)%cname= 'sss'                      ;   stypvar(25)%cname= 'sst'
-  stypvar(24)%cunits='PSU'                      ;   stypvar(25)%cunits='Celsius'
-  stypvar(24)%rmissing_value=0.                 ;   stypvar(25)%rmissing_value=0.
-  stypvar(24)%valid_min= 0.                     ;   stypvar(25)%valid_min= -2.
-  stypvar(24)%valid_max= 45                     ;   stypvar(25)%valid_max= 45
-  stypvar(24)%clong_name='Sea Surface Salinity' ;   stypvar(25)%clong_name='Sea Surface Temperature'
-  stypvar(24)%cshort_name='sss  '               ;   stypvar(25)%cshort_name='sst'
-
-  PRINT *, 'npiglo =', npiglo
-  PRINT *, 'npjglo =', npjglo
-  PRINT *, 'npt    =', npt
-
-
-  ALLOCATE ( zmask(npiglo,npjglo), wnet(npiglo,npjglo), zalbet(npiglo,npjglo), zbeta(npiglo, npjglo) )
-  ALLOCATE ( zcoefq(npiglo,npjglo), zcoefw(npiglo,npjglo) )
-  ALLOCATE ( evap(npiglo,npjglo), precip(npiglo,npjglo), runoff(npiglo,npjglo), wdmp(npiglo,npjglo) )
-  ALLOCATE ( wice(npiglo,npjglo), precip_runoff(npiglo,npjglo) )
-  ALLOCATE ( qlat(npiglo,npjglo), qsb(npiglo,npjglo), qlw(npiglo,npjglo), qsw(npiglo,npjglo), qnet(npiglo,npjglo) )
-  ALLOCATE ( b_evap(npiglo,npjglo), b_precip(npiglo,npjglo), b_runoff(npiglo,npjglo), b_wdmp(npiglo,npjglo),bw_net(npiglo,npjglo) ) 
-  ALLOCATE ( b_qlat(npiglo,npjglo), b_qsb(npiglo,npjglo),    b_qlw(npiglo,npjglo),    b_qsw(npiglo,npjglo), bh_net(npiglo,npjglo))
-  ALLOCATE ( buoyancy_fl(npiglo,npjglo), zsst(npiglo,npjglo), zsss(npiglo,npjglo) )
-
-  ncout = create      (cf_out, cf_tfil, npiglo,    npjglo, 1             )
-  ierr  = createvar   (ncout,  stypvar, jp_varout, ipk,    id_varout     )
-  ierr  = putheadervar(ncout,  cf_tfil, npiglo,    npjglo, 1,   pdep=zdep)
-
-  DO jt = 1, npt
-     ! read sss for masking purpose and sst
-     zsss(:,:) = getvar(cf_tfil, cn_vosaline, 1, npiglo, npjglo, ktime=jt)
-     zmask=1. ; WHERE ( zsss == 0 ) zmask=0.
-     zsst(:,:) = getvar(cf_tfil, cn_votemper, 1, npiglo, npjglo, ktime=jt)
-
-     ! Evap : 
-     qlat(:,:)= getvar(cf_tfil, cn_solhflup, 1, npiglo, npjglo, ktime=jt) *zmask(:,:)    ! W/m2 
-     evap(:,:)= -1.* qlat(:,:) /Lv*86400. *zmask(:,:)                                    ! mm/days
-
-     ! Wdmp
-     wdmp(:,:)= getvar(cf_tfil, cn_sowafldp, 1, npiglo, npjglo, ktime=jt)*86400.*zmask(:,:) ! mm/days
-
-     ! Runoff  ! take care : not a model output (time_counter may disagree ... jmm
-     runoff(:,:)= getvar(cf_rnfil, 'sorunoff', 1, npiglo, npjglo)*86400.*zmask(:,:)         ! mm/days
-
-     ! total water flux (emps)
-     wnet(:,:) = getvar(cf_tfil, cn_sowaflcd, 1, npiglo, npjglo, ktime=jt )*86400.*zmask(:,:)          ! mm/days
-
-     ! fsalt = contribution of ice freezing and melting to salinity ( + = freezing, - = melting )Q
-     wice(:,:) = getvar(cf_tfil, cn_iowaflup, 1, npiglo, npjglo, ktime=jt )*86400.*zmask(:,:)          ! mm/days
-
-     ! Precip:
-     precip(:,:)= evap(:,:)-runoff(:,:)+wdmp(:,:)-wnet(:,:)+wice(:,:)                     ! mm/day
-
-     ! Precip+runoff : (as a whole ) (interpolated on line)
-     precip_runoff(:,:)= evap(:,:)+wdmp(:,:)-wnet(:,:)+wice(:,:)                          ! mm/day
-
-     ! other heat fluxes
-     qsb(:,:)= getvar(cf_tfil, cn_sosbhfup,  1, npiglo, npjglo, ktime = jt )*zmask(:,:)    ! W/m2 
-     qlw(:,:)= getvar(cf_tfil, cn_solwfldo,  1, npiglo, npjglo, ktime = jt )*zmask(:,:)    ! W/m2 
-     qsw(:,:)= getvar(cf_tfil, cn_soshfldo,  1, npiglo, npjglo, ktime = jt )*zmask(:,:)    ! W/m2 
-     qnet(:,:)=getvar(cf_tfil, cn_sohefldo,  1, npiglo, npjglo, ktime = jt )*zmask(:,:)    ! W/m2 
-
-     ! buoyancy flux
-     zalbet(:,:)= albet ( zsst, zsss, 0., npiglo, npjglo)
-     zbeta (:,:)= beta  ( zsst, zsss, 0., npiglo, npjglo)
-     zcoefq(:,:)= -zbeta * zalbet /Cp * 1.e6
-     zcoefw(:,:)=  zbeta * zsss/(1-zsss/1000.)/86400. *1.e6   ! division by 86400 to get back water fluxes in kg/m2/s
-
-     buoyancy_fl=0. ; bh_net=0. ; b_qlat=0.  ; b_qlw=0.  ; b_qsw=0.   ; b_qsb=0.
-     bw_net=0.      ; b_evap=0. ; b_precip=0.; b_wdmp=0. ; b_runoff=0.
-
-     WHERE (zsss /= 0 ) 
-        bh_net(:,:)= zcoefq * qnet
-        b_qlat(:,:)= zcoefq * qlat
-        b_qlw (:,:)= zcoefq * qlw
-        b_qsw (:,:)= zcoefq * qsw
-        b_qsb (:,:)= zcoefq * qsb
-
-        bw_net(:,:)= zcoefw * wnet
-        b_evap(:,:)= zcoefw * evap
-        b_precip(:,:)= -zcoefw * precip
-        b_runoff(:,:)= -zcoefw * runoff
-        b_wdmp(:,:)= zcoefw * wdmp
-
-        !    buoyancy_fl(:,:) = zcoefq * qnet +zcoefw * wnet
-        buoyancy_fl(:,:) = bh_net + bw_net
-     END WHERE
-
-     ! Write output file
-
-     ierr = putvar(ncout, id_varout(1), evap,   1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(2), precip, 1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(3), runoff, 1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(4), wdmp,   1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(5), wnet,   1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(6), wice,   1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(7), precip_runoff,   1,npiglo, npjglo, ktime=jt )
-
-     ierr = putvar(ncout, id_varout(8), qlat,   1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(9), qsb,    1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(10),qlw,    1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(11),qsw,    1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(12),qnet,   1, npiglo, npjglo, ktime=jt )
-
-     ierr = putvar(ncout, id_varout(13),b_evap,  1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(14),b_precip,1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(15),b_runoff,1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(16),b_wdmp,  1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(17),bw_net,  1, npiglo, npjglo, ktime=jt )
-
-     ierr = putvar(ncout, id_varout(18),b_qlat,  1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(19),b_qsb,   1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(20),b_qlw,   1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(21),b_qsw,   1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(22),bh_net,  1, npiglo, npjglo, ktime=jt )
-
-     ierr = putvar(ncout, id_varout(23),buoyancy_fl, 1,npiglo, npjglo, ktime=jt )
-
-     ierr = putvar(ncout, id_varout(24), zsss,  1, npiglo, npjglo, ktime=jt )
-     ierr = putvar(ncout, id_varout(25), zsst,  1, npiglo, npjglo, ktime=jt )
-  END DO  ! time loop
-
-  tim  = getvar1d(cf_tfil, cn_vtimec, npt     )
-  ierr = putvar1d(ncout,   tim,       npt, 'T')
-
-  ierr=closeout(ncout)
-
-END PROGRAM cdfbuoyflx
diff --git a/cdfchgrid.f90 b/cdfchgrid.f90
deleted file mode 100644
index d7851c0..0000000
--- a/cdfchgrid.f90
+++ /dev/null
@@ -1,213 +0,0 @@
-PROGRAM cdfchgrid
-  !!======================================================================
-  !!                     ***  PROGRAM  cdfchgrid  ***
-  !!======================================================================
-  !!  ** Purpose : Transform an 1442x1021 ORCA025 grid variable into an 
-  !!               4322x3059 ORCA12 grid variable.
-  !!               No interpolation, only copying one grid cell into 9 grid cells.
-  !!
-  !!  ** Method  : Store the result on a 'cdfchgrid.nc' file similar to the input file
-  !!               (except x and y dimension)
-  !!
-  !!  ** Restriction  : Caution for mask coherence !
-  !!                    This tool is only adapted for drowned field
-  !!
-  !! History : 3.0 !  08/2012    A. Lecointre   : Original code with Full Doctor form + Lic.
-  !!----------------------------------------------------------------------
-  !!----------------------------------------------------------------------
-  !!   routines      : description
-  !!   chgrid        : Convert 1442x1021 ORCA025 2D var into 4322x3059 ORCA12 var
-  !!----------------------------------------------------------------------
-  USE cdfio
-  USE modcdfnames
-  !!----------------------------------------------------------------------
-  !! CDFTOOLS_3.0 , MEOM 2011
-  !! $Id: cdfchgrid.f90 XXX YYYY-MM-DD MM:MM:SSZ molines $
-  !! Copyright (c) 2010, J.-M. Molines
-  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
-  !!----------------------------------------------------------------------
-  IMPLICIT NONE
-
-  INTEGER(KIND=4)                               :: jk, jt                 ! dummy loop index
-  INTEGER(KIND=4)                               :: jvar,jjvar             ! dummy loop index
-  INTEGER(KIND=4)                               :: ierr                   ! working integer
-  INTEGER(KIND=4)                               :: narg, iargc, ijarg     ! argument on line
-  INTEGER(KIND=4)                               :: npiglo, npjglo         ! size of the input domain
-  INTEGER(KIND=4), PARAMETER                    :: npigloout=4322, npjgloout=3059 ! size of the output domain
-  INTEGER(KIND=4)                               :: npk, npt               ! size of the domain
-  INTEGER(KIND=4)                               :: nvars                  ! number of variables in the input file
-  INTEGER(KIND=4)                               :: ncout                  ! ncid of output ncdf file
-  INTEGER(KIND=4), DIMENSION(1)                 :: ipk                    ! output variable : number of levels
-  INTEGER(KIND=4), DIMENSION(1)                 :: id_varout              ! ncdf varid's
-
-  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: v2d                    ! array to read a layer of data 
-  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: u2d                    ! array onto ORCA12-grid
-  REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: tim                    ! time counter of the file
-  REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: dep                    ! depth of the file
-
-  CHARACTER(LEN=256)                            :: cf_out='cdfchgrid.nc'  ! output file name
-  CHARACTER(LEN=256)                            :: cf_in                  ! input file name
-  CHARACTER(LEN=256)                            :: cv_in                  ! variable name
-  CHARACTER(LEN=256)                            :: cldum                  ! working string
-  CHARACTER(LEN=256)                            :: cv_dep                 ! true name of dep dimension
-  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_names               ! array of var name
-
-  TYPE (variable), DIMENSION(:),    ALLOCATABLE :: stypvar                ! structure for variable attribute
-  !!--------------------------------------------------------------------------------------------------------------
-  CALL ReadCdfNames()
-
-  narg = iargc()
-  IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfchgrid -f IN-file -var IN-var'
-     PRINT *,'      '
-     PRINT *,'     PURPOSE :'
-     PRINT *,'       Convert ORCA025-grid variable into ORCA12-grid variable'
-     PRINT *,'       No interpolation, only copying one grid cell into nine grid cells'
-     PRINT *,'      '
-     PRINT *,'     RESTRICTION :'
-     PRINT *,'       Caution for mask coherence !'
-     PRINT *,'       This tool is only adapted for drowned field'
-     PRINT *,'      '
-     PRINT *,'     ARGUMENTS :'
-     PRINT *,'       -f IN-var : input ORCA025-grid file'
-     PRINT *,'       -var IN-var : input ORCA025-grid variable to be converted'
-     PRINT *,'      '
-     PRINT *,'     REQUIRED FILES :'
-     PRINT *,'       none '
-     PRINT *,'      '
-     PRINT *,'     OUTPUT : '
-     PRINT *,'       netcdf file : ', TRIM(cf_out)
-     PRINT *,'         variable : same name as in input file'
-     STOP
-  ENDIF
-  !!
-  ijarg = 1
-  ! Read command line
-  DO  WHILE (ijarg <=  narg)
-     CALL getarg(ijarg,cldum) ; ijarg = ijarg + 1
-     SELECT CASE ( cldum )
-     CASE ( '-f' )
-        CALL getarg(ijarg, cf_in) ; ijarg = ijarg + 1
-     CASE ( '-var' )
-        CALL getarg(ijarg,cv_in) ; ijarg = ijarg + 1
-     CASE DEFAULT
-        PRINT *, TRIM(cldum),' : unknown option '
-        STOP
-     END SELECT
-  END DO
-
-  IF ( chkfile(cf_in) ) STOP  ! missing files
-
-  ! get domain dimension from input file
-  npiglo = getdim (cf_in, cn_x)
-  npjglo = getdim (cf_in, cn_y)
-  npk    = getdim (cf_in, cn_z, cdtrue=cv_dep, kstatus=ierr)  ! defautl cn_z is depth
-  npt    = getdim (cf_in, cn_t)
-
-  IF ( npk == 0 )  npk = 1  ! assume a 2D variable
-  IF ( npt == 0 )  npt = 1  ! assume a 1 time frame file
-
-  PRINT *, 'npiglo = ', npiglo
-  PRINT *, 'npjglo = ', npjglo
-  PRINT *, 'npk    = ', npk
-  PRINT *, 'npt    = ', npt
-
-  ALLOCATE ( v2d(npiglo,npjglo) )
-  ALLOCATE ( u2d(npigloout,npjgloout) )
-  ALLOCATE ( tim(npt) )
-  ALLOCATE ( dep(npk) )
-
-  ! look for the number of variables in the input file
-  nvars = getnvar(cf_in)
-  ALLOCATE (cv_names(nvars) ,stypvar(nvars))
-  cv_names(:)=getvarname(cf_in,nvars,stypvar)
-
-  ! find the number of variable we are interested in
-  jvar=0
-  DO  WHILE (jvar <=  nvars)
-     jvar=jvar+1
-     IF ( cv_names(jvar) == cv_in ) jjvar=jvar
-  END DO
-  ipk(1)=npk
-  ncout = create      (cf_out,   cf_in  , npigloout, npjgloout, npk         )
-  ierr  = createvar   (ncout   , stypvar(jjvar), 1 , ipk  , id_varout )
-
-  ! get time and write time and get deptht and write deptht
-  tim=getvar1d(cf_in,cn_t,npt) ; ierr=putvar1d(ncout,tim,npt,'T')
-  dep=getvar1d(cf_in,cv_dep,npk) ; ierr=putvar1d(ncout,dep,npk,'D')
-
-  PRINT *,' Working with ', TRIM(cv_in), npk
-  DO jt = 1, npt
-     DO jk = 1, npk
-        v2d(:,:) = getvar(cf_in, cv_in,  jk, npiglo, npjglo, ktime=jt)
-        PRINT *,'level ',jk, 'time ',jt
-        CALL chgrid(v2d,u2d,'025to12')
-        ierr = putvar ( ncout , id_varout(1), REAL(u2d), jk, npigloout, npjgloout, ktime=jt)
-     ENDDO
-  ENDDO 
-
-  ierr    = closeout(ncout)
-
-CONTAINS
-
-  SUBROUTINE chgrid (invar,outvar,cc)
-
-  REAL(KIND=4), DIMENSION(npiglo,npjglo), INTENT(in)        :: invar
-  REAL(KIND=4), DIMENSION(npigloout,npjgloout), INTENT(out) :: outvar
-  CHARACTER(LEN=*), INTENT(in)                              :: cc
-  INTEGER(KIND=4)                                           :: iin,jin,iout,jout ! dummy loop index
-
-  SELECT CASE (cc)
-  CASE ('025to12')
-     DO iin = 2, 1441
-        iout=3*iin-4
-        jin=1   ! Fill only NORTH and EAST and WEST
-        jout=3*jin-2
-        outvar(iout  ,jout  ) = invar(iin,jin)
-        outvar(iout  ,jout+1) = invar(iin,jin)
-        outvar(iout-1,jout  ) = invar(iin,jin)
-        outvar(iout+1,jout  ) = invar(iin,jin)
-        outvar(iout+1,jout+1) = invar(iin,jin)
-        outvar(iout-1,jout+1) = invar(iin,jin)
-        DO jin = 2, 1020 ! Fill all: NORTH and SOUTH and EAST and WEST
-           jout=3*jin-2
-           outvar(iout  ,jout  ) = invar(iin,jin)
-           outvar(iout+1,jout  ) = invar(iin,jin)
-           outvar(iout-1,jout  ) = invar(iin,jin)
-           outvar(iout  ,jout-1) = invar(iin,jin)
-           outvar(iout  ,jout+1) = invar(iin,jin)
-           outvar(iout+1,jout+1) = invar(iin,jin)
-           outvar(iout+1,jout-1) = invar(iin,jin)
-           outvar(iout-1,jout+1) = invar(iin,jin)
-           outvar(iout-1,jout-1) = invar(iin,jin)
-        ENDDO
-     ENDDO
-     iin=1442
-     iout=3*iin-4
-     jin=1 ! Fill only NORTH and WEST
-     jout=3*jin-2
-     outvar(iout  ,jout  ) = invar(iin,jin)
-     outvar(iout  ,jout+1) = invar(iin,jin)
-     outvar(iout-1,jout  ) = invar(iin,jin)
-     outvar(iout-1,jout+1) = invar(iin,jin)
-     DO jin = 2, 1020 ! Fill only NORTH and SOUTH and WEST
-        jout=3*jin-2
-        outvar(iout  ,jout  ) = invar(iin,jin)
-        outvar(iout  ,jout-1) = invar(iin,jin)
-        outvar(iout  ,jout+1) = invar(iin,jin)
-        outvar(iout-1,jout  ) = invar(iin,jin)
-        outvar(iout-1,jout-1) = invar(iin,jin)
-        outvar(iout-1,jout+1) = invar(iin,jin)
-     ENDDO
-  CASE ('05to025')
-    ! to do ...
-  CASE ('05to12')
-    ! to do ...
-  CASE DEFAULT
-     PRINT *, TRIM(cc),'  is not recognized !'
-     PRINT *, 'No conversion will be performed'
-  END SELECT
-
-  END SUBROUTINE chgrid
-
-END PROGRAM cdfchgrid
diff --git a/cdfcurl.f90 b/cdfcurl.f90
deleted file mode 100644
index 2b8ee4d..0000000
--- a/cdfcurl.f90
+++ /dev/null
@@ -1,209 +0,0 @@
-PROGRAM cdfcurl
-  !!======================================================================
-  !!                     ***  PROGRAM  cdfcurl  ***
-  !!=====================================================================
-  !!  ** Purpose : Compute the curl on F-points for given gridU gridV 
-  !!               files and variables
-  !!
-  !!  ** Method  : Use the same algorithm than NEMO
-  !!
-  !! History : 2.1  : 05/2005  : J.M. Molines : Original code
-  !!         : 2.1  : 06/2007  : P. Mathiot   : for use with forcing fields
-  !!           3.0  : 01/2011  : J.M. Molines : Doctor norm + Lic.
-  !!----------------------------------------------------------------------
-  USE cdfio
-  USE modcdfnames
-  !!----------------------------------------------------------------------
-  !! CDFTOOLS_3.0 , MEOM 2011
-  !! $Id$
-  !! Copyright (c) 2011, J.-M. Molines
-  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
-  !!----------------------------------------------------------------------
-  IMPLICIT NONE
-
-  INTEGER(KIND=4)                           :: ji, jj, jt         ! dummy loop index
-  INTEGER(KIND=4)                           :: ilev               ! level to be processed
-  INTEGER(KIND=4)                           :: npiglo, npjglo     ! size of the domain
-  INTEGER(KIND=4)                           :: npk, npt           ! size of the domain
-  INTEGER(KIND=4)                           :: narg, iargc        ! browse command line
-  INTEGER(KIND=4)                           :: ncout, ierr        ! browse command line
-  INTEGER(KIND=4), DIMENSION(1)             :: ipk, id_varout     ! output variable properties
-
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e2v, e1u, e1f, e2f ! horizontql metrics
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: un, vn             ! velocity field
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zun, zvn           ! working arrays
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: rotn, fmask        ! curl and fmask
-  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim                ! time counter
-
-  CHARACTER(LEN=256)                        :: cf_ufil, cf_vfil   ! file names
-  CHARACTER(LEN=256)                        :: cf_out = 'curl.nc' ! output file name
-  CHARACTER(LEN=256)                        :: cv_u, cv_v         ! variable names
-  CHARACTER(LEN=256)                        :: cldum              ! dummy string
-
-  TYPE (variable), DIMENSION(1)             :: stypvar            ! structure for attibutes
-
-  LOGICAL                                   :: lforcing = .FALSE. ! forcing flag
-  LOGICAL                                   :: lchk     = .FALSE. ! flag for missing files
-  LOGICAL                                   :: lperio   = .FALSE. ! flag for E-W periodicity
-  !!----------------------------------------------------------------------
-  CALL ReadCdfNames() 
-
-  narg = iargc()
-  IF ( narg /= 5 ) THEN
-     PRINT *,' usage : cdfcurl U-file V-file U-var V-var lev'
-     PRINT *,'      '
-     PRINT *,'     PURPOSE :'
-     PRINT *,'       Compute the curl of a vector field, at a specified level.'  
-     PRINT *,'       If level is specified as 0, assume that the input files are'
-     PRINT *,'       forcing files, presumably on A-grid. In this latter case, the'
-     PRINT *,'       vector field is interpolated on the C-grid. In any case, the'
-     PRINT *,'       curl is computed on the F-point.'
-     PRINT *,'      '
-     PRINT *,'     ARGUMENTS :'
-     PRINT *,'       U-file : zonal component of the vector field.'
-     PRINT *,'       V-file : meridional component of the vector field.'
-     PRINT *,'       U-var  : zonal component variable name'
-     PRINT *,'       V-var  : meridional component variable name.'
-     PRINT *,'       lev    : level to be processed. If set to 0, assume forcing file '
-     PRINT *,'                in input.'
-     PRINT *,'      '
-     PRINT *,'     REQUIRED FILES :'
-     PRINT *,'        ', TRIM(cn_fhgr)
-     PRINT *,'      '
-     PRINT *,'     OUTPUT : '
-     PRINT *,'       netcdf file : ', TRIM(cf_out) 
-     PRINT *,'         variables : socurl (s^-1)'
-     STOP
-  ENDIF
-
-  CALL getarg(1, cf_ufil)
-  CALL getarg(2, cf_vfil)
-  CALL getarg(3, cv_u   )
-  CALL getarg(4, cv_v   )
-  CALL getarg(5, cldum  ) ;  READ(cldum,*) ilev
-
-  lchk = chkfile(cn_fhgr ) .OR. lchk
-  lchk = chkfile(cf_ufil ) .OR. lchk
-  lchk = chkfile(cf_vfil ) .OR. lchk
-  IF ( lchk ) STOP ! missing files
-
-  ! define new variables for output
-  stypvar(1)%cname             = 'socurl'
-  stypvar(1)%cunits            = 's-1'
-  stypvar(1)%rmissing_value    = 0.
-  stypvar(1)%valid_min         = -1000.
-  stypvar(1)%valid_max         =  1000.
-  stypvar(1)%clong_name        = 'Relative_Vorticity (curl)'
-  stypvar(1)%cshort_name       = 'socurl'
-  stypvar(1)%conline_operation = 'N/A'
-  stypvar(1)%caxis             = 'TYX'
-
-  ipk(1) = 1  !  2D
-
-  npiglo = getdim(cf_ufil,cn_x)
-  npjglo = getdim(cf_ufil,cn_y)
-  npk    = getdim(cf_ufil,cn_z)
-  npt    = getdim(cf_ufil,cn_t) 
-
-  PRINT *, 'npiglo = ',npiglo
-  PRINT *, 'npjglo = ',npjglo
-  PRINT *, 'npk    = ',npk
-  PRINT *, 'npt    = ',npt
-  PRINT *, 'ilev   = ',ilev
-
-  !test if lev exists
-  IF ( (npk==0) .AND. (ilev > 0) ) THEN
-     PRINT *, 'Problem : npk = 0 and lev > 0 STOP'
-     STOP
-  END IF
-
-  ! if forcing field 
-  IF ( ilev==0 .AND. npk==0 ) THEN
-     lforcing=.true.
-     npk = 1 ; ilev=1
-     PRINT *, 'npk =0, assume 1'
-  END IF
-
-  IF ( npt==0 ) THEN
-     PRINT *, 'npt=0, assume 1'
-     npt=1
-  END IF
-  ! check files and determines if the curl will be 2D of 3D
-  ! ????????????
-
-  ! Allocate the memory
-  ALLOCATE ( e1u(npiglo,npjglo) , e1f(npiglo,npjglo) )
-  ALLOCATE ( e2v(npiglo,npjglo) , e2f(npiglo,npjglo) )
-  ALLOCATE ( un(npiglo,npjglo)  , vn(npiglo,npjglo)  )
-  ALLOCATE ( zun(npiglo,npjglo) , zvn(npiglo,npjglo) )
-  ALLOCATE ( rotn(npiglo,npjglo) , fmask(npiglo,npjglo) )
-  ALLOCATE ( tim(npt) )
-
-  e1u =  getvar(cn_fhgr, cn_ve1u, 1, npiglo, npjglo)
-  e1f =  getvar(cn_fhgr, cn_ve1f, 1, npiglo, npjglo)
-  e2v =  getvar(cn_fhgr, cn_ve2v, 1, npiglo, npjglo)
-  e2f =  getvar(cn_fhgr, cn_ve2f, 1, npiglo, npjglo)
-
-  ! use zun and zvn to store f latitude and longitude for output
-  zun = getvar(cn_fhgr, cn_glamf, 1, npiglo, npjglo)
-  zvn = getvar(cn_fhgr, cn_gphif, 1, npiglo, npjglo)
-
-  ! look for  E-W periodicity
-  IF ( zun(1,1) == zun(npiglo-1,1) ) lperio = .TRUE.
-
-  ! create output fileset
-  ncout = create      (cf_out, cf_ufil, npiglo, npjglo, 0                           )
-  ierr  = createvar   (ncout , stypvar, 1,      ipk,    id_varout                   )
-  ierr  = putheadervar(ncout,  cf_ufil, npiglo, npjglo, 0, pnavlon=zun, pnavlat=zvn )
-
-  tim  = getvar1d(cf_ufil, cn_vtimec, npt      )
-  ierr = putvar1d(ncout,   tim,       npt,  'T')
-  
-  DO jt=1,npt
-     IF (MOD(jt,100)==0 ) PRINT *, jt,'/',npt
-        ! if files are forcing fields
-        zun(:,:) =  getvar(cf_ufil, cv_u, ilev ,npiglo,npjglo, ktime=jt)
-        zvn(:,:) =  getvar(cf_vfil, cv_v, ilev ,npiglo,npjglo, ktime=jt)
-
-     IF ( lforcing ) THEN ! for forcing file u and v are on the A grid
-        DO ji=1, npiglo-1
-           un(ji,:) = 0.5*(zun(ji,:) + zun(ji+1,:))
-        END DO
-        !
-        DO jj=1, npjglo-1
-           vn(:,jj) = 0.5*(zvn(:,jj) + zvn(:,jj+1))
-        END DO
-        ! end compute u and v on U and V point
-     ELSE
-       un(:,:) = zun(:,:)
-       vn(:,:) = zvn(:,:)
-     END IF
-
-     ! compute the mask
-     IF ( jt==1 ) THEN
-        DO jj = 1, npjglo - 1
-           DO ji = 1, npiglo - 1
-              fmask(ji,jj)=0.
-              fmask(ji,jj)= un(ji,jj)*un(ji,jj+1) * vn(ji,jj)*vn(ji+1,jj)
-              IF (fmask(ji,jj) /= 0.) fmask(ji,jj)=1.
-           ENDDO
-        ENDDO
-     END IF
-
-     rotn(:,:) = 0.
-     DO jj = 1, npjglo -1 
-        DO ji = 1, npiglo -1   ! vector opt.
-           rotn(ji,jj) = (  e2v(ji+1,jj  ) * vn(ji+1,jj  ) - e2v(ji,jj) * vn(ji,jj)    &
-                &         - e1u(ji  ,jj+1) * un(ji  ,jj+1) + e1u(ji,jj) * un(ji,jj)  ) &
-                &         * fmask(ji,jj) / ( e1f(ji,jj) * e2f(ji,jj) )
-        END DO
-     END DO
-
-     IF ( lperio ) rotn(npiglo,:) = rotn(2, :)
-     ! write rotn on file at level k and at time jt
-     ierr = putvar(ncout, id_varout(1), rotn, 1, npiglo, npjglo, ktime=jt)
-  END DO
-  ierr = closeout(ncout)
-
-END PROGRAM cdfcurl
-
diff --git a/cdfdiv.f90 b/cdfdiv.f90
deleted file mode 100644
index d0b4468..0000000
--- a/cdfdiv.f90
+++ /dev/null
@@ -1,199 +0,0 @@
-PROGRAM cdfdiv
-  !!======================================================================
-  !!                     ***  PROGRAM  cdfdiv  ***
-  !!=====================================================================
-  !!  ** Purpose : Compute the divergence for given gridU gridV files 
-  !!               and variables
-  !!
-  !!  ** Method  : Use the equation on continuity: Integrate the 
-  !!               horizontal divergence from bottom to the top.
-  !!               ( Use the same routines than in the NEMO code )
-  !!
-  !! History :  3.0  : 10/2011  : P. Mathiot : first version, based on cdfw.f90
-  !!          
-  !!----------------------------------------------------------------------
-  USE cdfio
-  USE modcdfnames
-  !!----------------------------------------------------------------------
-  !! CDFTOOLS_3.0 , MEOM 2011
-  !! $Id$
-  !! Copyright (c) 2011, J.-M. Molines
-  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
-  !!----------------------------------------------------------------------
-  IMPLICIT NONE
-
-  INTEGER(KIND=4)                              :: ji, jj, jk, jt     ! dummy loop index
-  INTEGER(KIND=4)                              :: npiglo, npjglo     ! size of the domain
-  INTEGER(KIND=4)                              :: npk, npt           ! size of the domain
-  INTEGER(KIND=4)                              :: narg, iargc, ijarg ! browse line
-  INTEGER(KIND=4)                              :: ncout              ! ncid of output file
-  INTEGER(KIND=4)                              :: ierr               ! error status
-  INTEGER(KIND=4)                              :: itmp               ! working integer for level swap
-  INTEGER(KIND=4), DIMENSION(1)                :: ipk, id_varout     ! levels and varid's of output vars
-
-  REAL(KIND=4), DIMENSION(:,:,:), ALLOCATABLE  :: wn                 ! vertical velocity on the top
-  !                                                                  ! and bottom of a cell.
-  !                                                                  ! wn(top) is computed
-  REAL(KIND=4), DIMENSION(:,:),    ALLOCATABLE :: e1t, e2t           ! horizontal T metrics
-  REAL(KIND=4), DIMENSION(:,:),    ALLOCATABLE :: e1v, e2u           ! horizontal V and U metrics
-  REAL(KIND=4), DIMENSION(:,:),    ALLOCATABLE :: e3v, e3u, e3t      ! vertical metrics
-  REAL(KIND=4), DIMENSION(:,:),    ALLOCATABLE :: glamt, gphit       ! T longitude latitude
-  REAL(KIND=4), DIMENSION(:,:),    ALLOCATABLE :: un, vn             ! horizontal velocity component
-  REAL(KIND=8), DIMENSION(:,:),    ALLOCATABLE :: hdivn              ! horizontal divergence
-  REAL(KIND=4), DIMENSION(:),      ALLOCATABLE :: gdepw              ! depth of W points
-  REAL(KIND=4), DIMENSION(:),      ALLOCATABLE :: tim                ! time counter
-  REAL(KIND=4), DIMENSION(:),      ALLOCATABLE :: e31d               ! vertical metrics (full step)
-
-  CHARACTER(LEN=256)                           :: cf_ufil            ! U file name
-  CHARACTER(LEN=256)                           :: cf_vfil            ! V file name
-  CHARACTER(LEN=256)                           :: cf_out='div.nc'      ! W file name ( output)
-  CHARACTER(LEN=256)                           :: cldum              ! dummy string
-
-  TYPE(variable), DIMENSION(1)                 :: stypvar            ! output attributes
-
-  LOGICAL                                      :: lchk               ! missing files flag
-  LOGICAL                                      :: lfull=.FALSE.      ! full step flag
-  !!----------------------------------------------------------------------
-  CALL ReadCdfNames()
-
-  narg = iargc()
-  IF ( narg < 2 ) THEN
-     PRINT *,' usage : cdfdiv U-file V-file [ U-var V-var ] [ -full ]'
-     PRINT *,'      '
-     PRINT *,'     PURPOSE :'
-     PRINT *,'       Compute the vertical velocity from the vertical integration of'
-     PRINT *,'       of the horizontal divergence of the velocity. '
-     PRINT *,'       Limitation: coded only for C grid (be carefful with forcing field)' 
-     PRINT *,'      '
-     PRINT *,'     ARGUMENTS :'
-     PRINT *,'       U-file : netcdf file with the zonal velocity component.' 
-     PRINT *,'       V-file : netcdf file with the meridional velocity component.' 
-     PRINT *,'      '
-     PRINT *,'     OPTIONS :'
-     PRINT *,'       [ U-var V-var ] : names of the zonal and meridional velocity '
-     PRINT *,'                         components. Default are ', TRIM(cn_vozocrtx),' and ', TRIM(cn_vomecrty)
-     PRINT *,'       [ -full ] : in case of full step configuration. Default is partial step.'
-     PRINT *,'      '
-     PRINT *,'     REQUIRED FILES :'
-     PRINT *,'       ',TRIM(cn_fhgr),' and ',TRIM(cn_fzgr) 
-     PRINT *,'      '
-     PRINT *,'     OUTPUT : '
-     PRINT *,'       netcdf file : ', TRIM(cf_out) 
-     PRINT *,'         variables : div (s-1)'
-     STOP
-  ENDIF
-
-  ijarg = 1
-  CALL getarg(ijarg, cf_ufil) ; ijarg = ijarg + 1
-  CALL getarg(ijarg, cf_vfil) ; ijarg = ijarg + 1
-
-  DO WHILE (ijarg <= narg )
-     CALL getarg(ijarg, cldum) ;
-     SELECT CASE ( cldum )
-     CASE ( '-full' ) 
-        lfull = .TRUE.
-        ijarg = ijarg + 1
-     CASE DEFAULT
-        CALL getarg(ijarg, cn_vozocrtx) ; ijarg = ijarg + 1
-        CALL getarg(ijarg, cn_vomecrty) ; ijarg = ijarg + 1
-     END SELECT
-  END DO
-
-  PRINT *, cn_vozocrtx, cn_vomecrty
-
-  lchk = chkfile (cn_fhgr)
-  lchk = chkfile (cn_fzgr) .OR. lchk
-  lchk = chkfile (cf_ufil) .OR. lchk
-  lchk = chkfile (cf_vfil) .OR. lchk
-  IF ( lchk ) STOP ! missing files
-
-  npiglo = getdim(cf_ufil,cn_x)
-  npjglo = getdim(cf_ufil,cn_y)
-  npk    = getdim(cf_ufil,cn_z)
-  npt    = getdim(cf_ufil,cn_t)
-
-  ! define new variables for output
-  ipk(1)                       = npk 
-  stypvar(1)%cname             = 'div'
-  stypvar(1)%cunits            = 's-1'
-  stypvar(1)%rmissing_value    = 0.
-  stypvar(1)%valid_min         = -10.
-  stypvar(1)%valid_max         = 10.
-  stypvar(1)%clong_name        = 'Divergence field'
-  stypvar(1)%cshort_name       = 'div' 
-  stypvar(1)%conline_operation = 'N/A'
-  stypvar(1)%caxis             = 'TZYX'
-
-  ! Allocate the memory
-  ALLOCATE ( e1v(npiglo,npjglo), e2u(npiglo,npjglo) )
-  ALLOCATE ( e1t(npiglo,npjglo), e2t(npiglo,npjglo) )
-  ALLOCATE ( e3u(npiglo,npjglo), e3v(npiglo,npjglo), e3t(npiglo,npjglo) )
-  ALLOCATE ( glamt(npiglo,npjglo), gphit(npiglo,npjglo)  )
-  ALLOCATE ( un(npiglo,npjglo), vn(npiglo,npjglo), hdivn(npiglo,npjglo) )
-  ALLOCATE ( wn(npiglo,npjglo,2) )
-  ALLOCATE ( gdepw(npk), tim(npt) )
-  IF ( lfull ) ALLOCATE ( e31d (npk) )
-
-  ! Read the metrics from the mesh_hgr file
-  e2u = getvar(cn_fhgr, cn_ve2u, 1, npiglo, npjglo)
-  e1v = getvar(cn_fhgr, cn_ve1v, 1, npiglo, npjglo)
-  e1t = getvar(cn_fhgr, cn_ve1t, 1, npiglo, npjglo)
-  e2t = getvar(cn_fhgr, cn_ve2t, 1, npiglo, npjglo)
-
-  ! and the coordinates   from the mesh_hgr file
-  glamt = getvar(cn_fhgr, cn_glamt, 1, npiglo, npjglo)
-  gphit = getvar(cn_fhgr, cn_gphit, 1, npiglo, npjglo)
-
-  ! Read the depth of the w points (in the file, it is not a vector but a 1x1xnpk array)
-  gdepw(:) = getvare3(cn_fzgr, cn_gdepw, npk)
-  IF ( lfull ) e31d(:) = getvare3(cn_fzgr, cn_ve3t, npk)
-
-  ! create output fileset
-  ncout = create      (cf_out, cf_ufil, npiglo, npjglo, npk, cdep=cn_vdepthw     )
-  ierr  = createvar   (ncout,  stypvar, 1,      ipk,    id_varout                )
-  ierr  = putheadervar(ncout,  'dummy', npiglo, npjglo, npk, glamt, gphit, gdepw )
-
-  tim  = getvar1d(cf_ufil, cn_vtimec, npt     )
-  ierr = putvar1d(ncout  , tim      , npt, 'T')
-
-  ! Main time loop
-  DO jt = 1, npt
-     ! Main level loop from top to bottom
-     DO jk = 1, npk
-        PRINT *,'jt = ', jt,' jk = ', jk
-
-        ! velocities at level jk
-        un(:,:) =  getvar(cf_ufil, cn_vozocrtx, jk, npiglo, npjglo, ktime=jt)
-        vn(:,:) =  getvar(cf_vfil, cn_vomecrty, jk, npiglo, npjglo, ktime=jt)
-
-        IF ( lfull ) THEN
-           e3u(:,:) = e31d(jk)
-           e3v(:,:) = e31d(jk)
-           e3t(:,:) = e31d(jk)
-        ELSE
-           ! e3 metrics at level jk ( Partial steps)
-           e3u(:,:) = getvar(cn_fzgr, 'e3u_ps', jk, npiglo, npjglo, ldiom=.TRUE.) 
-           e3v(:,:) = getvar(cn_fzgr, 'e3v_ps', jk, npiglo, npjglo, ldiom=.TRUE.) 
-           e3t(:,:) = getvar(cn_fzgr, 'e3t_ps', jk, npiglo, npjglo, ldiom=.TRUE.) 
-        ENDIF
-
-        ! Compute divergence :
-        DO jj = 2, npjglo -1
-           DO ji = 2, npiglo -1
-              hdivn(ji,jj) =   &
-                &  (  e2u(ji,jj)*e3u(ji,jj) * un(ji,jj) - e2u(ji-1,jj  )*e3u(ji-1,jj  )  * un(ji-1,jj )     &       
-                &   + e1v(ji,jj)*e3v(ji,jj) * vn(ji,jj) - e1v(ji  ,jj-1)*e3v(ji  ,jj-1)  * vn(ji  ,jj-1)  ) &
-                & / ( e1t(ji,jj)*e2t(ji,jj) * e3t(ji,jj) )
-           END DO
-        END DO
-
-        ! write level jk 
-        ierr = putvar(ncout, id_varout(1), hdivn, jk, npiglo, npjglo, ktime=jt)
-
-     END DO  ! loop to next level
-  END DO ! loop on time
-
-  ierr = closeout(ncout)
-
-END PROGRAM cdfdiv
-
diff --git a/cdfeke.f90 b/cdfeke.f90
deleted file mode 100644
index fb5c5ef..0000000
--- a/cdfeke.f90
+++ /dev/null
@@ -1,149 +0,0 @@
-PROGRAM cdfeke
-  !!======================================================================
-  !!                     ***  PROGRAM cdfeke   ***
-  !!=====================================================================
-  !!  ** Purpose : Compute Eddy Kinetic Energy 
-  !!
-  !!  ** Method  : Use gridU gridU2, gridV gridV2 files produced by
-  !!               cdfmoy. Velocities are interpolated both on T points
-  !!               and the variance is computed
-  !!
-  !! History : pre  : 11/2004  : J.M. Molines : Original code
-  !!           2.1  : 04/2005  : J.M. Molines : use modules
-  !!           3.0  : 12/2010  : J.M. Molines : Doctor norm + Lic.
-  !!----------------------------------------------------------------------
-  USE cdfio 
-  USE modcdfnames
-  !!----------------------------------------------------------------------
-  !! CDFTOOLS_3.0 , MEOM 2011
-  !! $Id$
-  !! Copyright (c) 2010, J.-M. Molines
-  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
-  !!----------------------------------------------------------------------
-  IMPLICIT NONE
-
-  INTEGER(KIND=4)                            :: ji, jj, jk, jt     ! dummy loop index
-  INTEGER(KIND=4)                            :: narg, iargc        ! command line browsing
-  INTEGER(KIND=4)                            :: npiglo, npjglo     ! size of the domain (horiz)
-  INTEGER(KIND=4)                            :: npk, npt           ! size of the domain vert and time
-  INTEGER(KIND=4)                            :: ncout              ! ncid of output file
-  INTEGER(KIND=4)                            :: ierr               ! Error status
-  INTEGER(KIND=4), DIMENSION(1)              :: ipk, id_varout     ! 
-
-  REAL(KIND=4)                               :: ua, va             ! working arrays
-  REAL(KIND=4), DIMENSION(:),    ALLOCATABLE :: tim                ! time variable
-  REAL(KIND=4), DIMENSION (:,:), ALLOCATABLE :: uc, vc, u2, v2     ! velocities etc...
-  REAL(KIND=4), DIMENSION (:,:), ALLOCATABLE :: eke                ! velocities etc...
-
-  CHARACTER(LEN=256)                         :: cf_out='eke.nc'    ! file name
-  CHARACTER(LEN=256)                         :: cf_ufil, cf_u2fil  ! file name
-  CHARACTER(LEN=256)                         :: cf_vfil, cf_v2fil  !
-  CHARACTER(LEN=256)                         :: cf_tfil            !
-
-  TYPE(variable), DIMENSION(1)               :: stypvar            !
-
-  LOGICAL                                    :: lchk               ! checking files existence
-  LOGICAL                                    :: lperio=.FALSE.     ! checking E-W periodicity
-  !!----------------------------------------------------------------------
-  CALL ReadCdfNames()
-
-  !!  Read command line
-  narg= iargc()
-  IF ( narg /= 5 ) THEN
-     PRINT *,' usage : cdfeke U-file U2-file V-file V2-file T2-file'
-     PRINT *,'      '
-     PRINT *,'     PURPOSE :'
-     PRINT *,'        Compute the Eddy Kinetic Energy from previously computed'
-     PRINT *,'        mean values and mean squared values of velocity components.'
-     PRINT *,'      '
-     PRINT *,'     ARGUMENTS :'
-     PRINT *,'       U-file  : gridU type file with mean U component.' 
-     PRINT *,'       U2-file : gridU2 type file with mean U2 component.' 
-     PRINT *,'       V-file  : gridV type file with mean V component.' 
-     PRINT *,'       V2-file : gridV2 type file with mean V2 component.' 
-     PRINT *,'       T2-file : any gridT or gridT2 (smaller) file, used for EKE header.'
-     PRINT *,'      '
-     PRINT *,'     REQUIRED FILES :'
-     PRINT *,'        none'
-     PRINT *,'      '
-     PRINT *,'     OUTPUT : '
-     PRINT *,'       netcdf file : ', TRIM(cf_out) 
-     PRINT *,'         variables : voeke (m2/s)'
-     STOP
-  ENDIF
-  !!
-  !! Initialisation from 1st file (all file are assume to have the same geometry)
-  CALL getarg (1, cf_ufil )
-  CALL getarg (2, cf_u2fil)
-  CALL getarg (3, cf_vfil )
-  CALL getarg (4, cf_v2fil)
-  CALL getarg (5, cf_tfil )
-
-  lchk =           chkfile (cf_ufil )
-  lchk = lchk .OR. chkfile (cf_u2fil)
-  lchk = lchk .OR. chkfile (cf_vfil )
-  lchk = lchk .OR. chkfile (cf_v2fil)
-  lchk = lchk .OR. chkfile (cf_tfil )
-  IF ( lchk ) STOP ! missing files
-
-  npiglo = getdim (cf_ufil,cn_x)
-  npjglo = getdim (cf_ufil,cn_y)
-  npk    = getdim (cf_ufil,cn_z)
-  npt    = getdim (cf_ufil,cn_t)
-
-  ipk(1)                       = npk
-  stypvar(1)%cname             = 'voeke'
-  stypvar(1)%cunits            = 'm2/s2'
-  stypvar(1)%rmissing_value    = 0.
-  stypvar(1)%valid_min         = 0.
-  stypvar(1)%valid_max         = 10000.
-  stypvar(1)%clong_name        = 'Eddy_Kinetic_Energy'
-  stypvar(1)%cshort_name       = 'voeke'
-  stypvar(1)%conline_operation = 'N/A'
-  stypvar(1)%caxis             = 'TZYX'
-
-  PRINT *, 'npiglo = ', npiglo
-  PRINT *, 'npjglo = ', npjglo
-  PRINT *, 'npk    = ', npk
-  PRINT *, 'npt    = ', npt
-
-  ALLOCATE( uc(npiglo,npjglo), u2(npiglo,npjglo), vc(npiglo,npjglo), v2(npiglo,npjglo) )
-  ALLOCATE( eke(npiglo,npjglo) , tim(npt) )
-
-  ncout = create      (cf_out, cf_tfil, npiglo, npjglo, npk       )
-  ierr  = createvar   (ncout,  stypvar, 1,      ipk,    id_varout )
-  ierr  = putheadervar(ncout,  cf_tfil, npiglo, npjglo, npk       )
-
-  ! check for E_W periodicity
-  uc(:,:) = getvar(cf_tfil, cn_vlon2d, 1, npiglo, npjglo )
-  IF ( uc(1,1) ==  uc(npiglo-1,1) ) THEN 
-     lperio = .TRUE. 
-     PRINT *,' E-W periodicity detected '
-  ENDIF
-
-  DO jt = 1, npt  ! input file is likely to contain only one time frame but who knows ...
-    DO jk = 1, npk
-      uc(:,:) = getvar(cf_ufil,  cn_vozocrtx,               jk, npiglo, npjglo, ktime=jt )
-      vc(:,:) = getvar(cf_vfil,  cn_vomecrty,               jk, npiglo, npjglo, ktime=jt )
-      u2(:,:) = getvar(cf_u2fil, TRIM(cn_vozocrtx)//'_sqd', jk ,npiglo, npjglo, ktime=jt )
-      v2(:,:) = getvar(cf_v2fil, TRIM(cn_vomecrty)//'_sqd', jk ,npiglo, npjglo, ktime=jt )
-
-      ua = 0. ; va = 0. ; eke(:,:) = 0.
-      DO ji=2, npiglo
-        DO jj=2,npjglo
-          ua = 0.5* ((u2(ji,jj)-uc(ji,jj)*uc(ji,jj))+ (u2(ji-1,jj)-uc(ji-1,jj)*uc(ji-1,jj)))
-          va = 0.5* ((v2(ji,jj)-vc(ji,jj)*vc(ji,jj))+ (v2(ji,jj-1)-vc(ji,jj-1)*vc(ji,jj-1)))
-          eke(ji,jj) = 0.5 * ( ua + va )
-        END DO
-      END DO
-      IF ( lperio ) eke(1,:) = eke(npiglo-1,:)
-      ierr=putvar(ncout,id_varout(1), eke, jk ,npiglo, npjglo, ktime=jt )
-    END DO
-  END DO ! time loop
-
-  tim  = getvar1d(cf_ufil, cn_vtimec, npt     )
-  ierr = putvar1d(ncout,   tim,       npt, 'T')
-
-  ierr = closeout(ncout)
-
-END PROGRAM cdfeke
diff --git a/cdffindij.f90 b/cdffindij.f90
deleted file mode 100644
index 0c4f07d..0000000
--- a/cdffindij.f90
+++ /dev/null
@@ -1,89 +0,0 @@
-PROGRAM cdffindij
-  !!======================================================================
-  !!                     ***  PROGRAM  cdffindij  ***
-  !!=====================================================================
-  !!  ** Purpose : Return the window index (imin imax jmin jmax )
-  !!               for the geographical windows given on input 
-  !!               (longmin longmax latmin matmax)
-  !!
-  !!  ** Method  : Read the coordinate/mesh_hgr file and look for the glam,
-  !!               gphi variables.
-  !!               Then use a search algorithm to find the corresponding I J
-  !!               The point type ( T U V F ) is specified on the command 
-  !!               line as well as the name of the coordinate/mesh hgr file.
-  !!
-  !! History : 2.1  : 11/2005  : J.M. Molines : Original code
-  !!           3.0  : 12/2010  : J.M. Molines : Doctor norm + Lic.
-  !!----------------------------------------------------------------------
-  USE cdfio
-  USE cdftools
-  USE modcdfnames
-  !!----------------------------------------------------------------------
-  !! CDFTOOLS_3.0 , MEOM 2011
-  !! $Id$
-  !! Copyright (c) 2010, J.-M. Molines
-  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
-  !!----------------------------------------------------------------------
-  IMPLICIT NONE
-
-  INTEGER(KIND=4)    :: narg, iargc                ! command line
-  INTEGER(KIND=4)    :: ijarg, ireq                ! command line
-  INTEGER(KIND=4)    :: iimin, iimax, ijmin, ijmax ! model grid window
-
-  REAL(KIND=4)       :: xmin, xmax, ymin, ymax     ! geographical window
-
-  CHARACTER(LEN=256) :: cltype='F'                 ! point type to search for
-  CHARACTER(LEN=256) :: cldum                      ! dummy character variable
-  CHARACTER(LEN=256) :: clcoo                      ! dummy character variable
-  !!----------------------------------------------------------------------
-  CALL ReadCdfNames()
-  clcoo = cn_fcoo
-
-  !!  Read command line and output usage message if not compliant.
-  narg= iargc()
-  IF ( narg < 4 ) THEN
-     PRINT *,' usage :   cdffindij  xmin xmax ymin ymax  [-c COOR-file] [-p point_type]'
-     PRINT *,'      '
-     PRINT *,'     PURPOSE :'
-     PRINT *,'       Return the model limit (i,j space) of the geographical window ' 
-     PRINT *,'       given on the input line.'
-     PRINT *,'      '
-     PRINT *,'     ARGUMENTS :'
-     PRINT *,'       xmin xmax ymin ymax : geographical limits of the window, in lon/lat' 
-     PRINT *,'      '
-     PRINT *,'     OPTIONS :'
-     PRINT *,'       [-c COOR-file ] : specify a particular coordinate file' 
-     PRINT *,'                     default is ',TRIM(cn_fcoo)
-     PRINT *,'       [-p point type] : specify the point on the C-grid (T U V F)'
-     PRINT *,'                     default is ',TRIM(cltype)
-     PRINT *,'      '
-     PRINT *,'     REQUIRED FILES :'
-     PRINT *,'       ', TRIM(cn_fcoo),' or the specified coordinates file.' 
-     PRINT *,'      '
-     PRINT *,'     OUTPUT : '
-     PRINT *,'       Output is done on standard output.'
-     STOP
-  ENDIF
-
-  ijarg = 1 ; ireq = 0
-  DO WHILE ( ijarg <= narg ) 
-    CALL getarg(ijarg, cldum ) ; ijarg=ijarg+1
-    SELECT CASE ( cldum )
-    CASE ( '-c' ) ; CALL getarg(ijarg, clcoo  ) ; ijarg=ijarg+1
-    CASE ( '-p' ) ; CALL getarg(ijarg, cltype ) ; ijarg=ijarg+1
-    CASE DEFAULT
-       ireq=ireq+1
-       SELECT CASE (ireq)
-       CASE ( 1 ) ; READ(cldum,*) xmin
-       CASE ( 2 ) ; READ(cldum,*) xmax
-       CASE ( 3 ) ; READ(cldum,*) ymin
-       CASE ( 4 ) ; READ(cldum,*) ymax
-       CASE DEFAULT 
-         PRINT *,' Too many arguments !' ; STOP
-       END SELECT
-    END SELECT
-  END DO
-
-  CALL cdf_findij ( xmin, xmax, ymin, ymax, iimin, iimax, ijmin, ijmax, cd_coord=clcoo, cd_point=cltype, cd_verbose='y')
-
-END PROGRAM cdffindij
diff --git a/cdfgradT.f90 b/cdfgradT.f90
deleted file mode 100644
index 16e298c..0000000
--- a/cdfgradT.f90
+++ /dev/null
@@ -1,216 +0,0 @@
-PROGRAM cdfgradT
-  !!======================================================================
-  !!                     ***  PROGRAM  cdfgradT  ***
-  !!=====================================================================
-  !!  ** Purpose :
-  !!
-  !!  ** Method  :
-  !!
-  !! History : 3.0  : 05/2013  : N. Ducousso
-  !!----------------------------------------------------------------------
-  USE cdfio
-  USE modcdfnames
-  !!----------------------------------------------------------------------
-  !!----------------------------------------------------------------------
-  IMPLICIT NONE
-
-  INTEGER(KIND=4)                            :: jk, jt, jvar      ! dummy loop index
-  INTEGER(KIND=4)                            :: narg, iargc       ! command line
-  INTEGER(KIND=4)                            :: ijarg, ireq       ! command line
-  INTEGER(KIND=4)                            :: npiglo, npjglo    ! size of the domain
-  INTEGER(KIND=4)                            :: npk, npt          ! size of the domain
-  INTEGER(KIND=4)                            :: ncout             ! ncid of output variable
-  INTEGER(KIND=4)                            :: ierr              ! error status
-  INTEGER(KIND=4)                            :: iup= 1, icurr= 2  ! 
-  INTEGER(KIND=4), DIMENSION(6)              :: ipk, id_varout    ! output variable
-
-  REAL(KIND=4), DIMENSION (:),      ALLOCATABLE :: tim              
-  REAL(KIND=4), DIMENSION (:,:,:),  ALLOCATABLE :: zt, zs
-  REAL(KIND=4), DIMENSION (:,:),    ALLOCATABLE :: umask, vmask, wmask
-  REAL(KIND=4), DIMENSION (:,:),    ALLOCATABLE :: e1u, e2v, e3w 
-
-  REAL(KIND=8), DIMENSION (:,:),    ALLOCATABLE :: gradt_x, gradt_y, gradt_z
-  REAL(KIND=8), DIMENSION (:,:),    ALLOCATABLE :: grads_x, grads_y, grads_z
- 
-  CHARACTER(LEN=256)                         :: cf_tfil             ! input file name
-  CHARACTER(LEN=256)                         :: cf_out = 'gradT.nc' ! output file name
-  CHARACTER(LEN=256), DIMENSION(2)           :: cv_namesi           ! input variable names
-
-  TYPE(variable), DIMENSION(6)               :: stypvar             ! output data structure
-
-  LOGICAL                                    :: lchk = .FALSE.      ! flag for missing files
-  !!----------------------------------------------------------------------
-  CALL ReadCdfNames()
-
-  cv_namesi(1) = cn_votemper
-  cv_namesi(2) = cn_vosaline
-
-  narg= iargc()
-  IF ( narg /= 1 ) THEN
-     PRINT *,' usage : cdfgradT T-file'
-     PRINT *,'      '
-     PRINT *,'     PURPOSE :'
-     PRINT *,'      '
-     PRINT *,'     ARGUMENTS :'
-     PRINT *,'      '
-     PRINT *,'     REQUIRED FILES :'
-     PRINT *,'      '
-     PRINT *,'     OUTPUT : '
-     PRINT *,'      '
-     STOP
-  ENDIF
-
-  CALL getarg (1, cf_tfil)
-  IF (chkfile(cf_tfil) ) STOP ! missing file
-
-  npiglo = getdim (cf_tfil, cn_x)
-  npjglo = getdim (cf_tfil, cn_y)
-  npk    = getdim (cf_tfil, cn_z)
-  npt    = getdim (cf_tfil, cn_t)
-
-  !!  Create output variables
-  ipk(:) = npk  !  3D
-
-  stypvar(1)%cname             = 'vozogradt'
-  stypvar(1)%cunits            = ''
-  stypvar(1)%rmissing_value    = -1000.
-  stypvar(1)%valid_min         = -1.
-  stypvar(1)%valid_max         = 1.
-  stypvar(1)%clong_name        = 'zonal temper gradient'
-  stypvar(1)%cshort_name       = 'vozogradt'
-  stypvar(1)%conline_operation = 'N/A'
-  stypvar(1)%caxis             = 'TZYX'
-
-  stypvar(2)%cname             = 'vomegradt'
-  stypvar(2)%cunits            = ''
-  stypvar(2)%rmissing_value    = -1000.
-  stypvar(2)%valid_min         = -1.
-  stypvar(2)%valid_max         = 1.
-  stypvar(2)%clong_name        = 'meridional temper gradient'
-  stypvar(2)%cshort_name       = 'vomegradt'
-  stypvar(2)%conline_operation = 'N/A'
-  stypvar(2)%caxis             = 'TZYX'
-
-  stypvar(3)%cname             = 'vovegradt'
-  stypvar(3)%cunits            = ''
-  stypvar(3)%rmissing_value    = -1000.
-  stypvar(3)%valid_min         = -1.
-  stypvar(3)%valid_max         = 1.
-  stypvar(3)%clong_name        = 'vertical temper gradient'
-  stypvar(3)%cshort_name       = 'vovegradt'
-  stypvar(3)%conline_operation = 'N/A'
-  stypvar(3)%caxis             = 'TZYX'
-
-  stypvar(4)%cname             = 'vozograds'
-  stypvar(4)%cunits            = ''
-  stypvar(4)%rmissing_value    = -1000.
-  stypvar(4)%valid_min         = -1.
-  stypvar(4)%valid_max         = 1.
-  stypvar(4)%clong_name        = 'zonal saline gradient'
-  stypvar(4)%cshort_name       = 'vozograds'
-  stypvar(4)%conline_operation = 'N/A'
-  stypvar(4)%caxis             = 'TZYX'
-
-  stypvar(5)%cname             = 'vomegrads'
-  stypvar(5)%cunits            = ''
-  stypvar(5)%rmissing_value    = -1000.
-  stypvar(5)%valid_min         = -1.
-  stypvar(5)%valid_max         = 1.
-  stypvar(5)%clong_name        = 'meridional saline gradient'
-  stypvar(5)%cshort_name       = 'vomegrads'
-  stypvar(5)%conline_operation = 'N/A'
-  stypvar(5)%caxis             = 'TZYX'
-
-  stypvar(6)%cname             = 'vovegrads'
-  stypvar(6)%cunits            = ''
-  stypvar(6)%rmissing_value    = -1000.
-  stypvar(6)%valid_min         = -1.
-  stypvar(6)%valid_max         = 1.
-  stypvar(6)%clong_name        = 'vertical saline gradient'
-  stypvar(6)%cshort_name       = 'vovegrads'
-  stypvar(6)%conline_operation = 'N/A'
-
-  PRINT *, 'npiglo = ', npiglo
-  PRINT *, 'npjglo = ', npjglo
-  PRINT *, 'npk    = ', npk
-  PRINT *, 'npt    = ', npt
-
-  !!  Allocate arrays
-  ALLOCATE (tim(npt) )
-  ALLOCATE (e1u(npiglo,npjglo), e2v(npiglo,npjglo), e3w(npiglo,npjglo))
-  ALLOCATE (umask(npiglo,npjglo), vmask(npiglo,npjglo), wmask(npiglo,npjglo))
-  ALLOCATE (zt(npiglo,npjglo,2), zs(npiglo,npjglo,2))
-  ALLOCATE (gradt_x(npiglo,npjglo), gradt_y(npiglo,npjglo), gradt_z(npiglo,npjglo))
-  ALLOCATE (grads_x(npiglo,npjglo), grads_y(npiglo,npjglo), grads_z(npiglo,npjglo))
-
-  ! create output fileset
-  ncout = create      (cf_out, cf_tfil, npiglo, npjglo, npk       )
-  ierr  = createvar   (ncout,  stypvar, 6,      ipk,    id_varout )
-  ierr  = putheadervar(ncout,  cf_tfil, npiglo, npjglo, npk       )
-
-  tim  = getvar1d(cf_tfil, cn_vtimec, npt     )
-  ierr = putvar1d(ncout,  tim,       npt, 'T')
-
-  e1u =  getvar(cn_fhgr, cn_ve1u, 1, npiglo, npjglo)
-  e2v =  getvar(cn_fhgr, cn_ve2v, 1, npiglo, npjglo)
-
-  DO jt = 1,npt
-  DO jk = npk, 1, -1  !! Main loop : (2 levels of T are required : iup, icurr)
-     
-     PRINT *,'level ',jk
-     
-     ! read files
-     IF (jk == 1) THEN
-        zt(:,:,iup)   = getvar(cf_tfil, cn_votemper, jk, npiglo, npjglo, ktime=jt)
-        zt(:,:,icurr) = getvar(cf_tfil, cn_votemper, jk, npiglo, npjglo, ktime=jt)
-        zs(:,:,iup)   = getvar(cf_tfil, cn_vosaline, jk, npiglo, npjglo, ktime=jt)
-        zs(:,:,icurr) = getvar(cf_tfil, cn_vosaline, jk, npiglo, npjglo, ktime=jt)
-     ELSE        
-        zt(:,:,iup)   = getvar(cf_tfil, cn_votemper, jk-1, npiglo, npjglo, ktime=jt)
-        zt(:,:,icurr) = getvar(cf_tfil, cn_votemper, jk, npiglo, npjglo, ktime=jt)
-        zs(:,:,iup)   = getvar(cf_tfil, cn_vosaline, jk-1, npiglo, npjglo, ktime=jt)
-        zs(:,:,icurr) = getvar(cf_tfil, cn_vosaline, jk, npiglo, npjglo, ktime=jt)
-     END IF
-
-     e3w(:,:) = getvar(cn_fzgr, 'e3w_ps', jk, npiglo, npjglo, ldiom=.true.)
-     
-     umask(:,:) = getvar(cn_fmsk, 'umask' , jk, npiglo, npjglo )
-     vmask(:,:) = getvar(cn_fmsk, 'vmask' , jk, npiglo, npjglo )
-     wmask(:,:) = getvar(cn_fmsk, 'tmask' , jk, npiglo, npjglo )
-
-     ! zonal grad located at U point
-     gradt_x(:,:) = 0.
-     gradt_x(1:npiglo-1,:) = 1. / e1u(1:npiglo-1,:) * &
-          &                 ( zt(2:npiglo,:,icurr) - zt(1:npiglo-1,:,icurr) ) * umask(1:npiglo-1,:)
-     grads_x(:,:) = 0.
-     grads_x(1:npiglo-1,:) = 1. / e1u(1:npiglo-1,:) * &
-          &                 ( zs(2:npiglo,:,icurr) - zs(1:npiglo-1,:,icurr) ) * umask(1:npiglo-1,:)
-
-     ! meridional grad located at V point
-     gradt_y(:,:) = 0.
-     gradt_y(:,1:npjglo-1) = 1. / e2v(:,1:npjglo-1) * &
-          &                 ( zt(:,2:npjglo,icurr) - zt(:,1:npjglo-1,icurr) ) * vmask(:,1:npjglo-1)
-     grads_y(:,:) = 0.
-     grads_y(:,1:npjglo-1) = 1. / e2v(:,1:npjglo-1) * &
-          &                 ( zs(:,2:npjglo,icurr) - zs(:,1:npjglo-1,icurr) ) * vmask(:,1:npjglo-1)
-
-     ! vertical grad located at W point
-     gradt_z(:,:) = 0.
-     gradt_z(:,:) = 1. / e3w(:,:) * ( zt(:,:,iup) - zt(:,:,icurr) ) * wmask(:,:)
-     grads_z(:,:) = 0.
-     grads_z(:,:) = 1. / e3w(:,:) * ( zs(:,:,iup) - zs(:,:,icurr) ) * wmask(:,:)
-
-     ! write
-     ierr = putvar(ncout, id_varout(1), REAL(gradt_x), jk, npiglo, npjglo, ktime=jt)
-     ierr = putvar(ncout, id_varout(2), REAL(gradt_y), jk, npiglo, npjglo, ktime=jt)
-     ierr = putvar(ncout, id_varout(3), REAL(gradt_z), jk, npiglo, npjglo, ktime=jt)
-     ierr = putvar(ncout, id_varout(4), REAL(grads_x), jk, npiglo, npjglo, ktime=jt)
-     ierr = putvar(ncout, id_varout(5), REAL(grads_y), jk, npiglo, npjglo, ktime=jt)
-     ierr = putvar(ncout, id_varout(6), REAL(grads_z), jk, npiglo, npjglo, ktime=jt)
-
-  END DO
-  END DO
-
-  ierr = closeout(ncout)
-
-END PROGRAM cdfgradT
diff --git a/cdfheatc.f90 b/cdfheatc.f90
deleted file mode 100644
index aa6ff16..0000000
--- a/cdfheatc.f90
+++ /dev/null
@@ -1,181 +0,0 @@
-PROGRAM cdfheatc
-  !!======================================================================
-  !!                     ***  PROGRAM  cdfheatc  ***
-  !!=====================================================================
-  !!  ** Purpose : Compute the heat content of the ocean : 1 single value
-  !!
-  !!  ** Method  : compute the sum ( rho cp T  * e1t *e2t * e3t * tmask )
-  !!
-  !! History : 2.1  : 03/2006  : J.M. Molines : Original code
-  !!           3.0  : 01/2011  : J.M. Molines : Doctor norm + Lic.
-  !!----------------------------------------------------------------------
-  USE cdfio
-  USE modcdfnames
-  !!----------------------------------------------------------------------
-  !! CDFTOOLS_3.0 , MEOM 2011
-  !! $Id$
-  !! Copyright (c) 2011, J.-M. Molines
-  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
-  !!----------------------------------------------------------------------
-  IMPLICIT NONE
-
-  INTEGER(KIND=4)                           :: jk, jt              ! dummy loop index
-  INTEGER(KIND=4)                           :: ik                  ! working integer
-  INTEGER(KIND=4)                           :: ierr                ! working integer
-  INTEGER(KIND=4)                           :: iimin=0, iimax=0    ! domain limitation for computation
-  INTEGER(KIND=4)                           :: ijmin=0, ijmax=0    ! domain limitation for computation
-  INTEGER(KIND=4)                           :: ikmin=0, ikmax=0    ! domain limitation for computation
-  INTEGER(KIND=4)                           :: narg, iargc, ijarg  ! command line 
-  INTEGER(KIND=4)                           :: npiglo, npjglo      ! size of the domain
-  INTEGER(KIND=4)                           :: npk, npt            ! size of the domain
-  INTEGER(KIND=4)                           :: nvpk                ! vertical levels in working variable
-
-  REAL(KIND=4), PARAMETER                   :: pprho0=1020.        ! water density (kg/m3)
-  REAL(KIND=4), PARAMETER                   :: ppcp=4000.          ! calorific capacity (J/kg/m3)
-
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e1t, e2t            ! horizontal metrics
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e3t                 ! vertical metric
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: temp                ! temperature
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: tmask               ! tmask
-  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: gdept               ! depth
-  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim                 ! time counter
-  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: e31d                ! vertical metrics in case of full step
-
-  REAL(KIND=8)                              :: dvol                ! 3D volume of the ocean
-  REAL(KIND=8)                              :: dsum                ! weighted sum 3D
-  REAL(KIND=8)                              :: dvol2d              ! volume of a layer
-  REAL(KIND=8)                              :: dsum2d              ! weigthed sum per layer
-  REAL(KIND=8)                              :: dsurf               ! surface of a layer
-
-  CHARACTER(LEN=256)                        :: cf_tfil             ! input gridT file
-  CHARACTER(LEN=256)                        :: cldum               ! dummy character variable
-
-  LOGICAL                                   :: lfull=.FALSE.       ! flag for full step computation
-  LOGICAL                                   :: lchk                ! flag for missing files
-  !!----------------------------------------------------------------------
-  CALL ReadCdfNames()
-
-  narg = iargc()
-  IF ( narg == 0 ) THEN
-     PRINT *,' usage :  cdfheatc  T-file ...'
-     PRINT *,'    ... [imin imax jmin jmax kmin kmax] [-full] '
-     PRINT *,'      '
-     PRINT *,'     PURPOSE :'
-     PRINT *,'        Computes the heat content in the specified area (Joules)'
-     PRINT *,'        A sub-domain can be specified in option.'
-     PRINT *,'      '
-     PRINT *,'     ARGUMENTS :'
-     PRINT *,'       T-file : a file with temperature and salinity' 
-     PRINT *,'      '
-     PRINT *,'     OPTIONS :'
-     PRINT *,'       [imin imax jmin jmax kmin kmax] : limit of a sub domain where'
-     PRINT *,'                      the heat content will be calculated.'
-     PRINT *,'                   - if imin = 0 then ALL i are taken'
-     PRINT *,'                   - if jmin = 0 then ALL j are taken'
-     PRINT *,'                   - if kmin = 0 then ALL k are taken'
-     PRINT *,'       [-full ] : assume full step model output instead of default'
-     PRINT *,'                  partial steps.'
-     PRINT *,'      '
-     PRINT *,'     REQUIRED FILES :'
-     PRINT *,'       Files ',TRIM(cn_fhgr),', ',TRIM(cn_fzgr),' and ',TRIM(cn_fmsk) 
-     PRINT *,'      '
-     PRINT *,'     OUTPUT : '
-     PRINT *,'       netcdf file : to be done ....'
-     PRINT *,'       Standard output'
-     STOP
-  ENDIF
-
-  ijarg = 1 
-  CALL getarg (ijarg, cf_tfil) ; ijarg = ijarg + 1
-
-  lchk = chkfile(cn_fhgr)
-  lchk = chkfile(cn_fzgr) .OR. lchk
-  lchk = chkfile(cn_fmsk) .OR. lchk
-  lchk = chkfile(cf_tfil) .OR. lchk
-  IF ( lchk ) STOP ! missing files
-
-  DO WHILE ( ijarg <= narg ) 
-     CALL getarg ( ijarg, cldum) ; ijarg = ijarg + 1
-     SELECT CASE ( cldum )
-     CASE ( '-full' ) ; lfull = .true.
-     CASE DEFAULT
-        PRINT *,' Reading 6 values : imin imax jmin jmax kmin kmax '
-                                                          READ(cldum,*) iimin
-        CALL getarg ( ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) iimax
-        CALL getarg ( ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) ijmin
-        CALL getarg ( ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) ijmax
-        CALL getarg ( ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) ikmin
-        CALL getarg ( ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) ikmax
-     END SELECT
-  END DO
-
-  npiglo = getdim (cf_tfil,cn_x)
-  npjglo = getdim (cf_tfil,cn_y)
-  npk    = getdim (cf_tfil,cn_z)
-  npt    = getdim (cf_tfil,cn_t)
-
-  IF (iimin /= 0 ) THEN ; npiglo = iimax - iimin + 1;  ELSE ; iimin=1 ; ENDIF
-  IF (ijmin /= 0 ) THEN ; npjglo = ijmax - ijmin + 1;  ELSE ; ijmin=1 ; ENDIF
-  IF (ikmin /= 0 ) THEN ; npk    = ikmax - ikmin + 1;  ELSE ; ikmin=1 ; ENDIF
-
-  nvpk   = getvdim(cf_tfil,cn_votemper)
-  IF (nvpk == 2 ) nvpk = 1
-  IF (nvpk == 3 ) nvpk = npk
-
-  PRINT *, 'npiglo = ', npiglo
-  PRINT *, 'npjglo = ', npjglo
-  PRINT *, 'npk    = ', npk
-  PRINT *, 'npt    = ', npt
-  PRINT *, 'nvpk   = ', nvpk
-
-  ! Allocate arrays
-  ALLOCATE ( tmask(npiglo,npjglo) )
-  ALLOCATE ( temp (npiglo,npjglo) )
-  ALLOCATE ( e1t  (npiglo,npjglo), e2t(npiglo,npjglo), e3t(npiglo,npjglo) )
-  ALLOCATE ( gdept(npk), tim(npt) )
-  IF ( lfull ) ALLOCATE ( e31d(npk) )
-
-  e1t(:,:) = getvar(cn_fhgr, cn_ve1t, 1, npiglo, npjglo, kimin=iimin, kjmin=ijmin)
-  e2t(:,:) = getvar(cn_fhgr, cn_ve2t, 1, npiglo, npjglo, kimin=iimin, kjmin=ijmin)
-  gdept(:) = getvare3(cn_fzgr, cn_gdept,  npk)
-  tim  (:) = getvare3(cf_tfil, cn_vtimec, npt)
-  IF ( lfull ) e31d(:) = getvare3(cn_fzgr, cn_ve3t, npk)
-
-  DO jt=1,npt
-     dvol = 0.d0
-     dsum = 0.d0
-     PRINT * ,'TIME : ', tim(jt)/86400.,' days'
-
-     DO jk = 1,nvpk
-        ik = jk + ikmin -1
-        ! Get velocities v at ik
-        temp( :,:)   = getvar(cf_tfil, cn_votemper, ik, npiglo, npjglo, kimin=iimin, kjmin=ijmin, ktime=jt)
-        tmask(:,:)   = getvar(cn_fmsk, 'tmask',     ik, npiglo, npjglo, kimin=iimin, kjmin=ijmin          )
-
-        ! get e3t at level ik ( ps...)
-        IF ( lfull ) THEN
-           e3t(:,:) = e31d(jk)
-        ELSE
-           e3t(:,:) = getvar(cn_fzgr, 'e3t_ps', ik, npiglo, npjglo, kimin=iimin, kjmin=ijmin, ldiom=.TRUE.)
-        ENDIF
-
-        dsurf  = SUM(e1t * e2t       * tmask)
-        dvol2d = SUM(e1t * e2t * e3t * tmask)
-        dvol   = dvol + dvol2d
-
-        dsum2d = SUM(e1t * e2t * e3t * temp * tmask)
-        dsum   = dsum + dsum2d
-
-        IF (dvol2d /= 0 )THEN
-           PRINT *, ' Heat Content  at level ',ik,'(',gdept(ik),' m) ',pprho0*ppcp*dsum2d, 'surface = ',dsurf/1.e6,' km^2'
-        ELSE
-           PRINT *, ' No points in the water at level ',ik,'(',gdept(ik),' m) '
-        ENDIF
-
-     END DO
-     
-     PRINT * ,' Total Heat content        : ', pprho0*ppcp*dsum ,' Joules'
-     PRINT * ,' Total Heat content/volume : ', pprho0*ppcp*dsum/dvol ,' Joules/m3 '
-  END DO
-
-END PROGRAM cdfheatc
diff --git a/cdfmltmask.f90 b/cdfmltmask.f90
deleted file mode 100644
index c9769a6..0000000
--- a/cdfmltmask.f90
+++ /dev/null
@@ -1,178 +0,0 @@
-PROGRAM cdfmltmask
-  !!======================================================================
-  !!                     ***  PROGRAM  cdfmltmask  ***
-  !!=====================================================================
-  !!  ** Purpose : multiplication of file by a mask (0,1)
-  !!
-  !! History : 2.1  : 06/2007  : M. Juza      : Original code
-  !!         : 2.1  : 06/2007  : P. Mathiot   : add forcing capabilities
-  !!           3.0  : 01/2011  : J.M. Molines : Doctor norm + Lic.
-  !!----------------------------------------------------------------------
-  USE cdfio
-  USE modcdfnames
-  !!----------------------------------------------------------------------
-  !! CDFTOOLS_3.0 , MEOM 2011
-  !! $Id$
-  !! Copyright (c) 2011, J.-M. Molines
-  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
-  !!----------------------------------------------------------------------
-  IMPLICIT NONE
-
-  INTEGER(KIND=4)                             :: jk, jt          ! dummy loop index
-  INTEGER(KIND=4)                             :: ierr            ! error status
-  INTEGER(KIND=4)                             :: narg, iargc     ! command line 
-  INTEGER(KIND=4)                             :: npiglo, npjglo  ! size of the domain
-  INTEGER(KIND=4)                             :: npk, npt        ! size of the domain
-  INTEGER(KIND=4)                             :: nvpk            ! vertical levels in working variable
-  INTEGER(KIND=4)                             :: npkmask         ! vertical levels in mask file
-
-  REAL(KIND=4)                                :: zspval          ! missing value attribute
-  REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: zv              ! cv_in at jk level 
-  REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: zmask           ! mask at jk level 
-  REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: zvmask          ! masked cv_in at jk level
-
-  CHARACTER(LEN=256)                          :: cunits          ! units attribute
-  CHARACTER(LEN=256)                          :: clname          ! long_name attribute
-  CHARACTER(LEN=256)                          :: csname          ! short_name attribute
-  CHARACTER(LEN=256)                          :: cf_in           ! input file name
-  CHARACTER(LEN=256)                          :: cf_msk          ! input mask file name
-  CHARACTER(LEN=256)                          :: cv_in           ! cdf variable name
-  CHARACTER(LEN=256)                          :: cvartype        ! variable position on Cgrid
-  CHARACTER(LEN=256)                          :: cv_dep          ! depth dim name
-  CHARACTER(LEN=256)                          :: ctmp            ! dummy string
-  CHARACTER(LEN=20)                           :: cv_msk          ! mask variable name
-  !!----------------------------------------------------------------------
-  CALL ReadCdfNames()
-
-  narg = iargc()
-  IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfmltmask IN-file MSK-file IN-var T| U | V | F | W | P'
-     PRINT *,'      '
-     PRINT *,'     PURPOSE :'
-     PRINT *,'       Multiply IN-var of IN-file by the mask corresponding to the' 
-     PRINT *,'       C-grid point position given as last argument.'
-     PRINT *,'      '
-     PRINT *,'     ARGUMENTS :'
-     PRINT *,'       IN-file  : input netcdf file.' 
-     PRINT *,'       MSK-file : input netcdf mask file.' 
-     PRINT *,'       IN-var   : input variable name.'
-     PRINT *,'       T| U | V | F | W | P : C-grid position of IN-var'
-     PRINT *,'                P indicate a polygon mask created by cdfpoly.'
-     PRINT *,'      '
-     PRINT *,'     REQUIRED FILES :'
-     PRINT *,'        none, all are given as arguments.'
-     PRINT *,'      '
-     PRINT *,'     OUTPUT : '
-     PRINT *,'       The output file is a copy of the input file with only'
-     PRINT *,'       the requested variable masked.'
-     PRINT *,'       netcdf file : IN-file_masked'
-     PRINT *,'         variables : IN-var (same as input).'
-     STOP
-  ENDIF
-
-  CALL getarg (1, cf_in    )
-  CALL getarg (2, cf_msk   )
-  CALL getarg (3, cv_in    )
-  CALL getarg (4, cvartype )
-
-  IF ( chkfile (cf_in) .OR. chkfile(cf_msk) ) STOP ! missing files
-
-  ! append _masked to input file name and copy initial file to new file, which will be modified
-  !  using dd more efficient than cp for big files
-  ctmp   = TRIM(cf_in)//'_masked'
-  CALL system(' dd bs=10000000 if='//TRIM(cf_in)//' of='//TRIM(ctmp) )
-  cf_in = ctmp
-
-  PRINT *,' Working on copy : ', TRIM(cf_in)
-
-  npiglo = getdim (cf_in,cn_x)
-  npjglo = getdim (cf_in,cn_y)
-  npk    = getdim (cf_in,cn_z, cdtrue=cv_dep, kstatus=ierr)
-
-  IF (ierr /= 0 ) THEN
-     npk   = getdim (cf_in, 'z', cdtrue=cv_dep, kstatus=ierr)
-     IF (ierr /= 0 ) THEN
-       npk   = getdim (cf_in, 'sigma', cdtrue=cv_dep, kstatus=ierr)
-        IF ( ierr /= 0 ) THEN
-          npk = getdim (cf_in, 'nav_lev', cdtrue=cv_dep, kstatus=ierr)
-            IF ( ierr /= 0 ) THEN
-              PRINT *,' assume file with no depth'
-              npk=0
-            ENDIF
-        ENDIF
-     ENDIF
-  ENDIF
-
-  npkmask = getdim (cf_msk, cn_z, cdtrue=cv_dep, kstatus=ierr)
-  IF (ierr /= 0 ) THEN
-     npkmask  = getdim (cf_msk, 'z', cdtrue=cv_dep, kstatus=ierr)
-       IF ( ierr /= 0 ) THEN
-            npkmask = getdim (cf_msk, 'nav_lev', cdtrue=cv_dep, kstatus=ierr)
-            IF ( ierr /= 0 ) THEN
-              PRINT *,' assume file with no depth'
-              npkmask=0
-            ENDIF
-       ENDIF
-  ENDIF
-
-  npt   = getdim (cf_in, cn_t )
-  nvpk  = getvdim(cf_in, cv_in)
-
-  IF (nvpk == 2 ) nvpk = 1
-  IF (nvpk == 3 ) nvpk = npk
-
-  PRINT *, 'npiglo = ', npiglo
-  PRINT *, 'npjglo = ', npjglo
-  PRINT *, 'npk    = ', npk
-  PRINT *, 'npt    = ', npt
-  PRINT *, 'nvpk   = ', nvpk
-
-  IF (npk==0) npk=1
-
-  ! Allocate arrays
-  ALLOCATE( zmask(npiglo,npjglo) )
-  ALLOCATE( zv   (npiglo,npjglo) )
-  ALLOCATE(zvmask(npiglo,npjglo) )
-
-  SELECT CASE (TRIM(cvartype))
-  CASE ( 'T' )
-     cv_msk='tmask'
-  CASE ( 'U' )
-     cv_msk='umask'
-  CASE ( 'V' )
-     cv_msk='vmask'
-  CASE ( 'F' )
-     cv_msk='fmask'
-  CASE ( 'W' )
-     cv_msk='tmask'
-  CASE ( 'P' )   ! for polymask 
-     cv_msk='polymask'
-  CASE DEFAULT
-     PRINT *, 'this type of variable is not known :', TRIM(cvartype)
-     STOP
-  END SELECT
-
-  IF ( npkmask <= 1 ) THEN 
-        zmask(:,:) = getvar(cf_msk, cv_msk, 1, npiglo, npjglo)
-  ENDIF
-
-  DO jt = 1, npt
-     IF (MOD(jt,100)==0) PRINT *, jt,'/', npt
-     DO jk = 1,nvpk
-        ! Read cv_in
-        zv(:,:) = getvar(cf_in, cv_in, jk, npiglo, npjglo, ktime=jt)
-        IF ( npkmask > 1 ) THEN
-        ! Read mask
-          zmask(:,:) = getvar(cf_msk, cv_msk, jk, npiglo, npjglo)
-        ENDIF
-        ! Multiplication of cv_in by mask at level jk
-        zvmask = zv * zmask
-        ! Writing  on the copy of original file                 
-        ierr = putvar(cf_in, cv_in, jk, npiglo, npjglo, 1, 1, ktime=jt, ptab=zvmask)
-     END DO
-  END DO
-  ! set missing value attribute for cv_in as 0.
-  ierr = getvaratt (cf_in, cv_in, cunits, zspval, clname, csname)
-  ierr = cvaratt   (cf_in, cv_in, cunits, 0.,     clname, csname)
-
-END PROGRAM cdfmltmask 
diff --git a/cdfmoy_freq.f90 b/cdfmoy_freq.f90
deleted file mode 100644
index 931d495..0000000
--- a/cdfmoy_freq.f90
+++ /dev/null
@@ -1,225 +0,0 @@
-PROGRAM cdfmoy_freq
-  !!======================================================================
-  !!                     ***  PROGRAM  cdfmoy_freq  ***
-  !!=====================================================================
-  !!  ** Purpose : Mainly in case of forcing file (gathered as yearly file)
-  !!               compute annual mean, monthl mean or diurnal means.
-  !!
-  !!  ** Method  : Detect the frequency of the input file according to the
-  !!               number of fields in the file.
-  !!
-  !! History : 2.1  : 06/2007  : P. Mathiot   : Original code from cdfmoy
-  !!           3.0  : 06/2011  : J.M. Molines : Doctor norm + Lic.
-  !!           3.0  : 10/2011  : P. Mathiot   : Add seasonal option and 
-  !!                                            allow file with 73 time steps
-  !!----------------------------------------------------------------------
-  USE cdfio 
-  USE modcdfnames
-  !!----------------------------------------------------------------------
-  !! CDFTOOLS_3.0 , MEOM 2011
-  !! $Id$
-  !! Copyright (c) 2011, J.-M. Molines
-  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
-  !!----------------------------------------------------------------------
-  IMPLICIT NONE
-
-  INTEGER(KIND=4)                               :: nt_in, nt_out
-  INTEGER(KIND=4)                               :: jk, jvar    ! dummy loop index
-  INTEGER(KIND=4)                               :: jv, jtt     ! dummy loop index
-  INTEGER(KIND=4)                               :: ierr            ! working integer
-  INTEGER(KIND=4)                               :: itime    ! dummy loop index
-  INTEGER(KIND=4)                               :: narg, iargc     ! 
-  INTEGER(KIND=4)                               :: npiglo, npjglo  ! size of the domain
-  INTEGER(KIND=4)                               :: npk ,npt        ! size of the domain
-  INTEGER(KIND=4)                               :: nvars           ! Number of variables in a file
-  INTEGER(KIND=4)                               :: ntframe         ! Cumul of time frame
-  INTEGER(KIND=4)                               :: ncout, ncout2
-  INTEGER(KIND=4), DIMENSION(365)               :: njd  ! day vector
-  INTEGER(KIND=4), DIMENSION( 12)               :: njm  ! month vector
-  INTEGER(KIND=4), DIMENSION(  4)               :: njs  !season vector
-  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_var, ipk, id_varout
-
-  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: v2d, rmean
-  REAL(KIND=4), DIMENSION(1)                    :: time
-  REAL(KIND=4), DIMENSION(365)                  :: tim
-
-  REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: dtab         ! Arrays for cumulated values
-  REAL(KIND=8)                                  :: dtotal_time
-
-  CHARACTER(LEN=256)                            :: cf_in               !
-  CHARACTER(LEN=256)                            :: cf_out              ! file name
-  CHARACTER(LEN=256)                            :: cv_dep
-  CHARACTER(LEN=256)                            :: cfreq_out, cfreq_in
-  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_names            ! array of var nam
-
-  TYPE (variable), DIMENSION(:),    ALLOCATABLE :: stypvar
-
-  LOGICAL                                       :: lcaltmean, lprint
-  !!----------------------------------------------------------------------
-  CALL ReadCdfNames()
-
-  narg= iargc()
-  IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfmoy_freq IN-file output_frequency'
-     PRINT *,'      '
-     PRINT *,'     PURPOSE :'
-     PRINT *,'       Compute annual mean or monthly mean or daily mean from a yearly'
-     PRINT *,'       input forcing file given on input.' 
-     PRINT *,'      '
-     PRINT *,'     ARGUMENTS :'
-     PRINT *,'       IN-file : netcdf input file corresponding to 1 year of forcing variable (1460, 365, 73 or 12 time step) '
-     PRINT *,'       output_frequency : either one of monthly, daily, seasonal or annual.'
-     PRINT *,'      '
-     PRINT *,'     REQUIRED FILES :'
-     PRINT *,'        none.'
-     PRINT *,'      '
-     PRINT *,'     OUTPUT : '
-     PRINT *,'       netcdf file :  cdfmoy_outputFreaquency.nc'
-     PRINT *,'         variables :  same as variables in input file.'
-     PRINT *,'      '
-     PRINT *,'     SEE ALSO :'
-     PRINT *,'      cdfmoy, cdfmoy_weighted'
-     PRINT *,'      '
-     STOP
-  ENDIF
-
-  !! Initialisation from 1st file (all file are assume to have the same geometry)
-  CALL getarg (1, cf_in    )
-  CALL getarg (2, cfreq_out)
-
-  IF ( chkfile ( cf_in ) ) STOP ! missing file
-
-  SELECT CASE ( cfreq_out )
-  CASE ('daily'   ) ; nt_out = 365
-  CASE ('monthly' ) ; nt_out =  12
-  CASE ('seasonal') ; nt_out =   4
-  CASE ('annual'  ) ; nt_out =   1
-  CASE DEFAULT 
-     PRINT *, 'Pb : this output_frequency is not allowed, please use daily, monthly, seasonal or annual'
-     STOP
-  END SELECT
-
-  npiglo= getdim (cf_in, cn_x                             )
-  npjglo= getdim (cf_in, cn_y                             )
-  npk   = getdim (cf_in, cn_z, cdtrue=cv_dep, kstatus=ierr)
-
-  IF (ierr /= 0 ) THEN
-     npk   = getdim (cf_in,'z',cdtrue=cv_dep,kstatus=ierr)
-     IF (ierr /= 0 ) THEN
-        npk   = getdim (cf_in,'sigma',cdtrue=cv_dep,kstatus=ierr)
-        IF ( ierr /= 0 ) THEN 
-           PRINT *,' assume file with no depth'
-           npk=0
-        ENDIF
-     ENDIF
-  ENDIF
-
-  npt   = getdim (cf_in, cn_t)
-
-  PRINT *, 'npiglo = ', npiglo
-  PRINT *, 'npjglo = ', npjglo
-  PRINT *, 'npk    = ', npk
-  PRINT *, 'npt    = ', npt
-
-  ALLOCATE( dtab(npiglo,npjglo), v2d(npiglo,npjglo) )
-  ALLOCATE( rmean(npiglo,npjglo)                    )
-
-  nvars = getnvar(cf_in)
-  PRINT *,' nvars =', nvars
-
-  ALLOCATE (cv_names(nvars)                            )
-  ALLOCATE (stypvar(nvars)                             )
-  ALLOCATE (id_var(nvars), ipk(nvars), id_varout(nvars))
-
-  ! get list of variable names and collect attributes in stypvar (optional)
-  cv_names(:)=getvarname(cf_in, nvars, stypvar)
-
-  id_var(:)  = (/(jv, jv=1,nvars)/)
-  ! ipk gives the number of level or 0 if not a T[Z]YX  variable
-  ipk(:)     = getipk (cf_in, nvars, cdep=cv_dep)
-  !
-  WHERE( ipk == 0 ) cv_names='none'
-  stypvar(:)%cname = cv_names
-
-  !
-  ! create output file taking the sizes in cf_in
-
-  cf_out = 'cdfmoy_'//TRIM(cfreq_out)//'.nc'
-  ncout = create      (cf_out, cf_in,   npiglo, npjglo, npk, cdep=cv_dep )
-  ierr  = createvar   (ncout,  stypvar, nvars,  ipk,    id_varout )
-  ierr  = putheadervar(ncout,  cf_in,   npiglo, npjglo, npk, cdep=cv_dep )
-
-  time=getvar1d(cf_in, cn_vtimec, 1)
-  ierr=putvar1d(ncout, time, 1, 'T')
-
-  npt   = getdim (cf_in, cn_t)
-  nt_in = npt
-
-  SELECT CASE ( npt )
-  CASE ( 1460 ) ; PRINT *, 'Frequency of this file : 6h '
-  CASE (  365 ) ; PRINT *, 'Frequency of this file : daily '
-  CASE (   73 ) ; PRINT *, 'Frequency of this file : 5 day '
-  CASE (   12 ) ; PRINT *, 'Frequency of this file : monthly '
-  END SELECT
-
-  IF (npt <= nt_out) THEN
-     PRINT *, 'You don''t need to use it, or it is impossible (npt_in <= npt_out)'
-     STOP
-  END IF
-
-  ! number of day by month, season and day
-  njd(:)= 1
-  njm= (/ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 /)
-  njs= (/ 90, 91, 92, 92 /)
-
-  DO jvar = 1,nvars
-     IF ( cv_names(jvar) == cn_vlon2d .OR.                            &
-          cv_names(jvar) == cn_vlat2d .OR. cv_names(jvar) == 'none') THEN
-        ! skip these variable
-     ELSE
-        PRINT *,' Working with ', TRIM(cv_names(jvar))
-	DO jk=1,ipk(jvar)
-
-    ! initialisation
-           dtab(:,:) = 0.d0 ; dtotal_time = 0.d0;  ntframe=0; itime=1; 
-
-	   ! time loop
-           DO jtt=1, nt_in
-	      lprint=.FALSE.
-              ntframe=ntframe+1
-              ! load data
-              v2d(:,:)  = getvar(cf_in, cv_names(jvar), jk, npiglo, npjglo, ktime=jtt )
-              dtab(:,:) = dtab(:,:) + v2d(:,:)*1.d0
-
-              ! detection of time when you have to print the average
-              IF (nt_out==365) THEN
-	         IF (MOD(jtt,FLOOR(SUM(njd(1:itime)) * nt_in/365.))==0) lprint=.TRUE.
-              ELSE IF (nt_out==12) THEN
-	         IF (MOD(jtt,FLOOR(SUM(njm(1:itime)) * nt_in/365.))==0) lprint=.TRUE.
-              ELSE IF (nt_out==4) THEN   
-	         IF (MOD(jtt,FLOOR(SUM(njs(1:itime)) * nt_in/365.))==0) lprint=.TRUE.
-              ELSE IF (nt_out==1) THEN
-	         IF (MOD(jtt,                          nt_in      )==0) lprint=.TRUE.
-              END IF
-              !
-              ! Compute and print the average at the right time              
-              IF ( lprint ) THEN
-                 IF (jk==1) PRINT *, itime, jtt,'/',npt 
-                 ! compute mean
-                 rmean(:,:) = dtab(:,:)/ntframe
-                 ! store variable on outputfile
-                 ierr = putvar(ncout, id_varout(jvar) ,rmean, jk, npiglo, npjglo, ktime=itime)
-                 dtab(:,:) = 0.d0 ; dtotal_time = 0.;  ntframe=0; itime=itime+1
-              END IF
-	      !
-           ENDDO ! loop to next time
-
-	ENDDO ! loop to next level
-
-     END IF
-  END DO ! loop to next var in file
-
-  ierr = closeout(ncout)
-
-
-END PROGRAM cdfmoy_freq
diff --git a/cdftools-begin.pod b/cdftools-begin.pod
deleted file mode 100644
index b33daff..0000000
--- a/cdftools-begin.pod
+++ /dev/null
@@ -1,21 +0,0 @@
-=head1  NAME
-
-cdftools - diagnostics in Fortran 90 for NEMO model outputs
-
-=head1 SYNOPSIS
-
- cdf* option...
-
-=head1 DESCRIPTION
-
-C<CDFTOOLS> is a diagnostic package written in fortran 90
-for the analysis of NEMO model output in the frame of the DRAKKAR project.
-
-This software is a computer program for analysis of NEMO model output 
-produced in the frame of the DRAKKAR project. It is designed  for the
-treatment of the NetCdf files produced by NEMO-DRAKKAR. 
-
-C<NEMO> web site : http://www.nemo-ocean.eu/
-
-=head1 COMMAND
-
diff --git a/cdftransport.f90 b/cdftransport.f90
deleted file mode 100644
index de36953..0000000
--- a/cdftransport.f90
+++ /dev/null
@@ -1,1176 +0,0 @@
-PROGRAM cdftransport
-   !!======================================================================
-   !!                     ***  PROGRAM  cdftransport  ***
-   !!=====================================================================
-   !!  ** Purpose : Compute Transports across a section. 
-   !!               By default, mass (Sv) and  heat(PW)/salt(kT/s) transports
-   !!               are computed unless -noheat option is used (mass 
-   !!               transport only).
-   !!
-   !!  ** Method  : The begining and end point of the section are given in 
-   !!               term of F-points index. A broken line joining successive
-   !!               F-points is defined between the begining and end point
-   !!               of the section. Therefore each segment between F-points
-   !!               is either a zonal or meridional segment corresponding to
-   !!               V or U velocity component. Doing so, the volume conservation
-   !!               is ensured as velocities are not interpolated, and stay 
-   !!               on the native model grid. 
-   !!                 The section name and the begin/end point of a section are
-   !!               read from standard input, till 'EOF' is given as section
-   !!               name. This make possible to give a bunch of sections in 
-   !!               an ASCII files and use the < redirection.
-   !!            SIGN CONVENTION : The transport is positive when the flow cross
-   !!               the section to the right, negative otherwise. This depends
-   !!               on the sense the section is described.  With this convention
-   !!               The algebric sum of transports accross sections forming a 
-   !!               closed area is 0. 
-   !!            OPTIONS :
-   !!               -full   : full step case
-   !!               -noheat : only mass transport is computed.
-   !!               -time   : specify the time frame to be used
-   !!               -zlimit : transports can be computed in different depth layers
-   !!                         defined by their depth limit
-   !!            REQUIREMENT :
-   !!               mesh-mask file are required in the current directory.
-   !!            
-   !!
-   !! History : 2.1  : 01/2005  : J.M. Molines : Original code
-   !!           2.1  : 07/2009  : R. Dussin : add cdf output
-   !!           2.1  : 01/2010  : M.A. Balmaseda : Change integration signs 
-   !!                             so that the transport across a segment is 
-   !!                             independent of the chosen trajectory.
-   !!           3.0  : 04/2011  : J.M. Molines : Doctor norm + Lic.
-   !!----------------------------------------------------------------------
-   !!----------------------------------------------------------------------
-   !!   routines      : description
-   !!  interm_pt  : choose intermediate points on a broken line.
-   !!----------------------------------------------------------------------
-   USE cdfio
-   USE modcdfnames
-   USE modutils       ! for global attribute
-   !!----------------------------------------------------------------------
-   !! CDFTOOLS_3.0 , MEOM 2011
-   !! $Id$
-   !! Copyright (c) 2011, J.-M. Molines
-   !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
-   !!----------------------------------------------------------------------
-   IMPLICIT NONE
-
-   INTEGER(KIND=4)                             :: jclass, jseg   ! dummy loop index
-   INTEGER(KIND=4)                             :: ji, jj, jk     ! dummy loop index
-   INTEGER(KIND=4), DIMENSION(:),  ALLOCATABLE :: imeter         ! limit beetween depth level, in m (nclass -1)
-   INTEGER(KIND=4), DIMENSION(:),  ALLOCATABLE :: ilev0, ilev1   ! limit in levels  (nclass)
-   INTEGER(KIND=4), DIMENSION(:),  ALLOCATABLE :: ipk, id_varout ! Netcdf output
-   INTEGER(KIND=4)                             :: ipos           ! working integer (position of ' ' in strings)
-   INTEGER(KIND=4)                             :: ncout, ierr    ! for netcdf output
-   INTEGER(KIND=4)                             :: nvarout=12     ! number of values to write in cdf output
-   INTEGER(KIND=4)                             :: ivtrp          ! var index of volume transport (barotrope)
-   INTEGER(KIND=4)                             :: iptrp          ! var index of volume transport (barotrope)
-   INTEGER(KIND=4)                             :: imtrp          ! var index of volume transport (barotrope)
-   INTEGER(KIND=4)                             :: ihtrp          ! var index of heat transport (barotrope)
-   INTEGER(KIND=4)                             :: istrp          ! var index of sal transport (barotrope)
-   INTEGER(KIND=4)                             :: ivtrpcl        ! var index of volume transport (p. class)
-   INTEGER(KIND=4)                             :: iptrpcl        ! var index of volume transport (p. class)
-   INTEGER(KIND=4)                             :: imtrpcl        ! var index of volume transport (p. class)
-   INTEGER(KIND=4)                             :: ihtrpcl        ! var index of heat transport (p. class)
-   INTEGER(KIND=4)                             :: istrpcl        ! var index of sal transport (p. class)
-   INTEGER(KIND=4)                             :: ilonmin        ! var index of starting section longitude
-   INTEGER(KIND=4)                             :: ilonmax        ! var index of ending section longitude
-   INTEGER(KIND=4)                             :: ilatmin        ! var index of starting section latitude
-   INTEGER(KIND=4)                             :: ilatmax        ! var index of ending section latitude
-   INTEGER(KIND=4)                             :: itop           ! var index of top depth class
-   INTEGER(KIND=4)                             :: ibot           ! var index of bottom depth class
-   INTEGER(KIND=4)                             :: ikx=1, iky=1   ! dims of netcdf output file
-   INTEGER(KIND=4)                             :: numout  = 10   ! logical unit for output file (overall)
-   INTEGER(KIND=4)                             :: numvtrp = 11   ! logical unit for volume transport file
-   INTEGER(KIND=4)                             :: numhtrp = 12   ! logical unit for heat transport file
-   INTEGER(KIND=4)                             :: numstrp = 14   ! logical unit for salt trp file 
-   INTEGER(KIND=4)                             :: nclass         ! number of depth class
-   INTEGER(KIND=4)                             :: narg, iargc    ! command line 
-   INTEGER(KIND=4)                             :: ijarg, nxtarg  !  "       "
-   INTEGER(KIND=4)                             :: npiglo, npjglo ! size of the domain
-   INTEGER(KIND=4)                             :: npk, npt       ! size of the domain
-   INTEGER(KIND=4)                             :: iimin, iimax   ! i-limit of the section
-   INTEGER(KIND=4)                             :: ijmin, ijmax   ! j-limit of the section
-   INTEGER(KIND=4)                             :: ivar, itime    ! working integer
-   INTEGER(KIND=4)                             :: ii, ij, ik     ! working integer
-   INTEGER(KIND=4), PARAMETER                  :: jpseg=10000    ! used for broken line algorithm
-   INTEGER(KIND=4)                             :: ii0, ij0       !  "        "             "
-   INTEGER(KIND=4)                             :: ii1, ij1       !  "        "             "
-   INTEGER(KIND=4)                             :: iitmp, ijtmp   !  "        "             "
-   INTEGER(KIND=4)                             :: np, nn         ! segment counters, 
-   INTEGER(KIND=4)                             :: iist, ijst     ! local point offset for velocity
-   INTEGER(KIND=4)                             :: norm_u, norm_v ! normalization factor (sign of normal transport)
-   INTEGER(KIND=4)                             :: idirx, idiry   ! sense of description of the section
-
-   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: e1v, e2u       ! horizontal metric
-   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: e3u, e3v       ! vertical metric
-   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: glamf          ! longitudes of F points
-   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: gphif          ! latitudes of F points
-   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: zu, zut, zus   ! Zonal velocities and uT uS
-   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: zv, zvt, zvs   ! Meridional velocities and uT uS
-   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: rdum           ! dummy (1x1) array for ncdf output
-   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: zuobc, zvobc   ! arrays for OBC files (vertical slice)
-   REAL(KIND=4), DIMENSION(:),     ALLOCATABLE :: tim            ! time counter
-   REAL(KIND=4), DIMENSION(:),     ALLOCATABLE :: gdepw          ! depth at layer interface
-   REAL(KIND=4), DIMENSION(:),     ALLOCATABLE :: e31d           ! vertical metric in case of full step
-   REAL(KIND=4), DIMENSION(:),     ALLOCATABLE :: rclass         ! vertical metric in case of full step
-   REAL(KIND=4), DIMENSION(2)                  :: gla, gphi      ! lon/lat of the begining/end of section (f point)
-   REAL(KIND=4), DIMENSION(jpseg)              :: rxx, ryy       ! working variables
-   REAL(KIND=4)                                :: rxi0, ryj0     ! working variables
-   REAL(KIND=4)                                :: rxi1, ryj1     ! working variables
-   REAL(KIND=4)                                :: ai, bi         ! equation of line (y=ai.x +bi)
-   REAL(KIND=4)                                :: aj, bj         ! equation of line (x=aj.y +bj
-   REAL(KIND=4)                                :: rd, rd1, rd2   ! distance between point, between vertical layers
-   REAL(KIND=4)                                :: udum, vdum     ! dummy velocity components for tests
-   REAL(KIND=4)                                :: rau0=1000      ! density of pure water (kg/m3)
-   REAL(KIND=4)                                :: rcp=4000.      ! heat capacity (J/kg/K)
-
-   ! at every model point
-   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dwku,  dwkv    ! volume transport at each cell boundary
-   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dwkut, dwkvt   ! heat   transport at each cell boundary
-   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dwkus, dwkvs   ! salt   transport at each cell boundary
-   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dwkup, dwkvp   ! volume transport in the positive direction
-   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dwkum, dwkvm   !  volume transport in the negatibe direction
-   REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dtrpu,  dtrpv  ! volume transport integrated in depth class
-   REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dtrput, dtrpvt ! heat transport integrated in depth class
-   REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dtrpus, dtrpvs ! salt transport integrated in depth class
-   REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dtrpup, dtrpvp ! volume transport integrated in depth class (positive)
-   REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dtrpum, dtrpvm ! volume transport integrated in depth class (negative)
-   ! for a given section
-   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dvoltrpsum     ! volume transport by depth class across section
-   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dvoltrpsump    ! volume transport by depth class across section
-   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dvoltrpsumm    ! volume transport by depth class across section
-   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dheatrpsum     ! heat transport by depth class across section
-   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dsaltrpsum     ! salt transport by depth class across section
-   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dvolallegcl    ! over all leg volume transport by depth class
-   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dvolallegclp   ! over all leg volume transport by depth class +
-   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dvolallegclm   ! over all leg volume transport by depth class -
-   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dheatallegcl   ! over all leg heat transport by depth class 
-   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dsaltallegcl   ! over all leg salt transport by depth class 
-   REAL(KIND=8), DIMENSION(jpseg)              :: dvoltrp        ! volume transport across each segment of a section
-   REAL(KIND=8), DIMENSION(jpseg)              :: dvoltrpp       ! volume transport across each segment of a section
-   REAL(KIND=8), DIMENSION(jpseg)              :: dvoltrpm       ! volume transport across each segment of a section
-   REAL(KIND=8), DIMENSION(jpseg)              :: dheatrp        ! heat transport across each segment of a section
-   REAL(KIND=8), DIMENSION(jpseg)              :: dsaltrp        ! salt transport across each segment of a section
-   REAL(KIND=8)                                :: dvoltrpbrtp    ! volume transport integrated over the whole depth
-   REAL(KIND=8)                                :: dvoltrpbrtpp   ! volume transport integrated over the whole depth
-   REAL(KIND=8)                                :: dvoltrpbrtpm   ! volume transport integrated over the whole depth
-   REAL(KIND=8)                                :: dheatrpbrtp    ! heat transport integrated over the whole depth
-   REAL(KIND=8)                                :: dsaltrpbrtp    ! salt transport integrated over the whole depth
-   REAL(KIND=8)                                :: dvolalleg      ! over all leg sum of volume transport
-   REAL(KIND=8)                                :: dvolallegp     ! over all leg sum of volume transport +
-   REAL(KIND=8)                                :: dvolallegm     ! over all leg sum of volume transport -
-   REAL(KIND=8)                                :: dheatalleg     ! over all leg sum of heat transport 
-   REAL(KIND=8)                                :: dsaltalleg     ! over all leg sum of salt transport 
-
-   COMPLEX, DIMENSION(jpseg)                   :: yypt           ! array of points coordinates in a section
-   COMPLEX                                     :: yypti          ! working point
-
-   TYPE(variable), DIMENSION(:),   ALLOCATABLE :: stypvar        ! structure of output
-
-   CHARACTER(LEN=256)                          :: cf_tfil        ! VT file  (in)
-   CHARACTER(LEN=256)                          :: cf_ufil        ! U file   (in)
-   CHARACTER(LEN=256)                          :: cf_vfil        ! V file   (in)
-   CHARACTER(LEN=256)                          :: cf_out='section_trp.dat'  ! output file name (ASCII)
-   CHARACTER(LEN=256)                          :: cf_outnc            ! output netcdf file
-   CHARACTER(LEN=256)                          :: cf_vtrp='vtrp.txt'  ! output volume transport file
-   CHARACTER(LEN=256)                          :: cf_htrp='htrp.txt'  ! output heat transport file
-   CHARACTER(LEN=256)                          :: cf_strp='strp.txt'  ! output salt transport file
-   CHARACTER(LEN=256)                          :: csection            ! section names
-   CHARACTER(LEN=256)                          :: cvarname            ! variable names (root)
-   CHARACTER(LEN=256)                          :: clongname           ! variable longname (root)
-   CHARACTER(LEN=512)                          :: cglobal             ! global attribute
-   CHARACTER(LEN=256)                          :: cldum               ! dummy char variable
-   CHARACTER(LEN=256)                          :: cline               ! dummy char variable
-   CHARACTER(LEN=256), DIMENSION(3)            :: cldumt              ! dummy char variable
-
-   LOGICAL                                     :: ltest   = .FALSE.   ! flag for test case
-   LOGICAL                                     :: lfull   = .FALSE.   ! flag for full step case
-   LOGICAL                                     :: lheat   = .TRUE.    ! flag for skipping heat/salt transport computation
-   LOGICAL                                     :: lchk    = .FALSE.   ! flag for missing files
-   LOGICAL                                     :: lpm     = .FALSE.   ! flag for plus/minus transport
-   LOGICAL                                     :: lobc    = .FALSE.   ! flag for obc input files
-   LOGICAL                                     :: l_merid = .FALSE.   ! flag for meridional obc
-   LOGICAL                                     :: l_zonal = .FALSE.   ! flag for zonal obc
-   !!----------------------------------------------------------------------
-   CALL ReadCdfNames()
-
-   narg= iargc()
-   ! Print usage if no argument
-   IF ( narg == 0 ) THEN
-      PRINT *,' usage : cdftransport [-test  u v ] [-noheat ] [-plus_minus ] [-obc]...'
-      PRINT *,'                  ... [VT-file] U-file V-file [-full] |-time jt] ...'
-      PRINT *,'                  ... [-time jt ] [-zlimit limits of level]'
-      PRINT *,'      '
-      PRINT *,'    PURPOSE :'
-      PRINT *,'      Compute the transports accross a section.'
-      PRINT *,'      The name of the section and the imin, imax, jmin, jmax for the section '
-      PRINT *,'      is read from the standard input. To finish the program use the key name'
-      PRINT *,'      ''EOF'' for the section name.'
-      PRINT *,'      OBC U,V files can be used if -obc option is specified.'
-      PRINT *,'      '
-      PRINT *,'     ARGUMENTS :'
-      PRINT *,'      [VT-file ] : netcdf file with mean values of vt, vs, ut, us for heat and'
-      PRINT *,'                   salt transport. If options -noheat or -plus_minus are used'
-      PRINT *,'                   this file name must be omitted.'   
-      PRINT *,'      [U-file ] : netcdf file with the zonal velocity component.'
-      PRINT *,'      [V-file ] : netcdf file with the meridional velocity component.'
-      PRINT *,'      '
-      PRINT *,'     OPTIONS :'
-      PRINT *,'      [-test u v ]: use constant the u and v velocity components for sign '
-      PRINT *,'                    test purpose.'
-      PRINT *,'      [-noheat ]  : use when heat and salt transport are not requested.'
-      PRINT *,'                    This option must come before the file names, and if used'
-      PRINT *,'                    VT file must not be given.'
-      PRINT *,'      [ -plus_minus or -pm ] : separate positive and negative contribution to'
-      PRINT *,'                    the volume transport. This option implicitly set -noheat,'
-      PRINT *,'                    and must be used before the file names.'
-      PRINT *,'      [-obc ]    : indicates that input files are obc files (vertical slices)'
-      PRINT *,'                    Take care that for this case, mesh files must be adapted.'
-      PRINT *,'                    This option implicitly set -noheat, and must be used before'
-      PRINT *,'                    the file names.'
-      PRINT *,'      [-full ]   :  use for full step configurations.'
-      PRINT *,'      [-time jt ]:  compute transports for time index jt. Default is 1.'
-      PRINT *,'      [-zlimit list of depth] : Specify depths limits defining layers where the'
-      PRINT *,'                    transports will be computed. If not used, the transports '
-      PRINT *,'                    are computed for the whole water column. If used, this '
-      PRINT *,'                    option must be the last on the command line.'  
-      PRINT *,'      '
-      PRINT *,'     REQUIRED FILES :'
-      PRINT *,'      Files ',TRIM(cn_fhgr),', ',TRIM(cn_fzgr),' must be in the current directory.'
-      PRINT *,'      '
-      PRINT *,'     OUTPUT : '
-      PRINT *,'      - Standard output '
-      PRINT *,'      - ASCII file reflecting the standard output: section_trp.dat'
-      PRINT *,'      - ASCII files for volume, heat and salt transport: vtrp.txt, htrp.txt '
-      PRINT *,'          and strp.txt.'
-      PRINT *,'      - Netcdf files for each section. name of the file is buildt'
-      PRINT *,'          from section name.'
-      PRINT *,'      '
-      PRINT *,'     SEE ALSO :'
-      PRINT *,'       cdfsigtrp'
-      PRINT *,'      '
-      STOP
-   ENDIF
-
-   itime  = 1
-   nclass = 1
-   ijarg  = 1
-   CALL SetGlobalAtt(cglobal)
-
-   ! Browse command line for arguments and/or options
-   DO WHILE (ijarg <= narg )
-      CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1
-      SELECT CASE ( cldum )
-      CASE ('-test ')
-         CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) udum
-         CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) vdum
-         ltest = .TRUE. 
-
-      CASE ('-full' )
-         lfull = .TRUE.
-
-      CASE ('-noheat' )  ! it must be called before the list of files
-         lheat = .FALSE.
-
-      CASE ('-time' )
-         CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) itime
-
-      CASE ('-plus_minus', '-pm' )
-         lpm   = .TRUE.
-         lheat = .FALSE.
-
-      CASE ('-obc' )
-         lobc   = .TRUE.
-         lheat = .FALSE.
-
-      CASE ('-zlimit' )  ! this should be the last option on the line
-         nxtarg = ijarg - 1
-         nclass = narg - nxtarg + 1
-         ALLOCATE ( imeter(nclass -1) ) ! if no zlimit option, this array is never used
-         DO jclass =1, nclass -1
-            CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) imeter(jclass)
-         END DO
-
-      CASE DEFAULT
-         ijarg = ijarg -1 ! re-read argument in this case
-         IF ( lheat) THEN 
-            CALL getarg (ijarg, cf_tfil) ; ijarg = ijarg + 1 
-         ENDIF
-         CALL getarg (ijarg, cf_ufil) ; ijarg = ijarg + 1 
-         CALL getarg (ijarg, cf_vfil) ; ijarg = ijarg + 1 
-      END SELECT
-   END DO
-
-   ! checking if all required files are available
-   lchk = lchk .OR. chkfile(cn_fzgr)
-   lchk = lchk .OR. chkfile(cn_fhgr)
-   IF ( ltest ) THEN
-      ! OK
-   ELSE
-      lchk = lchk .OR. chkfile(cf_ufil)
-      lchk = lchk .OR. chkfile(cf_vfil)
-      IF (lheat) THEN
-         lchk = lchk .OR. chkfile(cf_tfil)
-      ENDIF
-   ENDIF
-   IF ( lchk ) STOP ! missing files
-
-   ! adjust the number of output variables according to options
-   IF ( nclass > 1 ) THEN
-      IF ( lheat ) THEN
-         nvarout = 12
-      ELSE 
-         nvarout = 8
-      ENDIF
-      IF ( lpm ) nvarout=nvarout+4
-   ELSE
-      IF ( lheat ) THEN
-         nvarout = 9
-      ELSE 
-         nvarout = 7
-      ENDIF
-      IF ( lpm ) nvarout=nvarout+2
-   ENDIF
-
-   ALLOCATE ( ilev0(nclass), ilev1(nclass), rclass(nclass) )
-   rclass=(/(jclass, jclass=1,nclass)/)
-
-   npiglo = getdim (cf_ufil,cn_x)
-   npjglo = getdim (cf_ufil,cn_y)
-   npk    = getdim (cf_ufil,cn_z)
-   npt    = getdim (cf_ufil,cn_t)
-
-   PRINT *, 'npiglo =', npiglo
-   PRINT *, 'npjglo =', npjglo
-   PRINT *, 'npk    =', npk
-   PRINT *, 'npt    =', npt
-
-   IF ( lobc ) THEN  ! if lobc false, l_merid and l_zonal are false (default)
-      IF ( npiglo == 1 ) THEN
-         l_merid=.TRUE.
-         ALLOCATE (zuobc(npjglo,npk), zvobc(npjglo,npk) )
-         PRINT *,' Meridional OBC'
-      ENDIF
-
-      IF ( npjglo == 1 ) THEN
-         l_zonal=.TRUE.
-         ALLOCATE (zuobc(npiglo,npk), zvobc(npiglo,npk) )
-         PRINT *,' Zonal OBC'
-      ENDIF
-   ENDIF
-
-   ALLOCATE ( e31d(npk) )
-
-   ! define new variables for output 
-   ALLOCATE ( stypvar(nvarout), ipk(nvarout), id_varout(nvarout) )
-   ALLOCATE ( rdum(1,1) )
-
-   rdum(:,:)=0.e0
-
-   ! Allocate arrays
-   ALLOCATE (   zu(npiglo,npjglo),   zv(npiglo,npjglo) )
-   ALLOCATE ( dwku(npiglo,npjglo), dwkv(npiglo,npjglo) )
-   ALLOCATE ( dtrpu(npiglo,npjglo,nclass), dtrpv(npiglo,npjglo,nclass))
-   ALLOCATE ( dvoltrpsum(nclass), dvolallegcl(nclass) )
-
-   IF ( lpm ) THEN 
-      ALLOCATE ( dwkup(npiglo,npjglo), dwkvp(npiglo,npjglo) )
-      ALLOCATE ( dwkum(npiglo,npjglo), dwkvm(npiglo,npjglo) )
-      ALLOCATE ( dtrpup(npiglo,npjglo,nclass), dtrpvp(npiglo,npjglo,nclass))
-      ALLOCATE ( dtrpum(npiglo,npjglo,nclass), dtrpvm(npiglo,npjglo,nclass))
-      ALLOCATE ( dvoltrpsump(nclass),  dvoltrpsumm(nclass)  )
-      ALLOCATE ( dvolallegclp(nclass), dvolallegclm(nclass) )
-   ENDIF
-
-   IF ( lheat ) THEN
-      ALLOCATE (   zut(npiglo,npjglo),   zus(npiglo,npjglo) )
-      ALLOCATE (   zvt(npiglo,npjglo),   zvs(npiglo,npjglo) )
-      ALLOCATE ( dwkut(npiglo,npjglo), dwkus(npiglo,npjglo) )
-      ALLOCATE ( dwkvt(npiglo,npjglo), dwkvs(npiglo,npjglo) )
-      ALLOCATE ( dtrput(npiglo,npjglo,nclass), dtrpvt(npiglo,npjglo,nclass))
-      ALLOCATE ( dtrpus(npiglo,npjglo,nclass), dtrpvs(npiglo,npjglo,nclass))
-      ALLOCATE ( dheatrpsum(nclass), dsaltrpsum(nclass)     )
-      ALLOCATE ( dheatallegcl(nclass), dsaltallegcl(nclass) )
-   ENDIF
-   !
-   ALLOCATE ( e1v(npiglo,npjglo),e3v(npiglo,npjglo)       )
-   ALLOCATE ( e2u(npiglo,npjglo),e3u(npiglo,npjglo)       )
-   !
-   ALLOCATE ( gphif(npiglo,npjglo) )
-   ALLOCATE ( glamf(npiglo,npjglo) )
-   ALLOCATE ( gdepw(npk) , tim(npt)                       )
-   !
-   ! read metrics and grid position
-   e1v(:,:)   = getvar(cn_fhgr, cn_ve1v, 1, npiglo, npjglo)
-   e2u(:,:)   = getvar(cn_fhgr, cn_ve2u, 1, npiglo, npjglo)
-
-   glamf(:,:) = getvar(cn_fhgr, cn_glamf, 1,npiglo, npjglo)
-   gphif(:,:) = getvar(cn_fhgr, cn_gphif, 1,npiglo, npjglo)
-
-   gdepw(:) = getvare3(cn_fzgr, cn_gdepw, npk)
-   e31d(:)  = getvare3(cn_fzgr, cn_ve3t,  npk) ! used only for full step
-
-   ! look for nearest level to imeter and setup ilev0 and ilev1 (t-index of class limit)
-   ik = 1
-   ilev0(1) = 1 ; ilev1(nclass) = npk-1  ! default value if nclass=1
-
-   IF ( lobc ) THEN
-      ! read u, v on OBC
-      IF ( l_zonal ) THEN   ! (jpiglo,jpk)
-         zuobc(:,:)= getvarxz(cf_ufil, cn_vozocrtx, 1, npiglo, npk)
-         zvobc(:,:)= getvarxz(cf_vfil, cn_vomecrty, 1, npiglo, npk)
-      ENDIF
-      IF ( l_merid ) THEN   ! (jpjglo,jpk)
-         zuobc(:,:)= getvaryz(cf_ufil, cn_vozocrtx, 1, npjglo, npk)
-         zvobc(:,:)= getvaryz(cf_vfil, cn_vomecrty, 1, npjglo, npk)
-      ENDIF
-   ENDIF
-
-   DO jclass = 1, nclass -1
-      DO WHILE ( gdepw(ik)  < imeter(jclass) )
-         ik = ik +1
-      END DO
-
-      rd1 = ABS(gdepw(ik-1) - imeter(jclass) )
-      rd2 = ABS(gdepw(ik  ) - imeter(jclass) )
-      IF ( rd2 < rd1 ) THEN
-         ilev1(jclass  ) = ik - 1  ! t-levels index
-         ilev0(jclass+1) = ik
-      ELSE 
-         ilev1(jclass  ) = ik - 2  ! t-levels index
-         ilev0(jclass+1) = ik - 1
-      END IF
-   END DO
-
-   PRINT *, 'Limits :  '
-   DO jclass = 1, nclass
-      PRINT *, ilev0(jclass),ilev1(jclass), gdepw(ilev0(jclass)), gdepw(ilev1(jclass)+1)
-   END DO
-
-   ! compute the transports at each grid cell
-   dtrpu (:,:,:)= 0.d0 ; dtrpv (:,:,:)= 0.d0    ! initialization to 0
-
-   IF ( lpm   ) THEN
-      dtrpup(:,:,:)= 0.d0 ; dtrpvp(:,:,:)= 0.d0  
-      dtrpum(:,:,:)= 0.d0 ; dtrpvm(:,:,:)= 0.d0
-   ENDIF
-   IF ( lheat ) THEN
-      dtrput(:,:,:)= 0.d0 ; dtrpvt(:,:,:)= 0.d0  
-      dtrpus(:,:,:)= 0.d0 ; dtrpvs(:,:,:)= 0.d0
-   ENDIF
-
-   DO jclass = 1, nclass
-      DO jk = ilev0(jclass),ilev1(jclass)
-         PRINT *,'level ',jk
-         ! Get velocities, temperature and salinity fluxes at jk
-         IF ( ltest ) THEN
-            zu (:,:) = udum ; zv (:,:) = vdum
-            IF (lheat) THEN
-               zut(:,:) = udum ; zvt(:,:) = vdum
-               zus(:,:) = udum ; zvs(:,:) = vdum
-            ENDIF
-         ELSEIF ( lobc ) THEN
-            IF      ( l_zonal ) THEN ; zu(:,1)=zuobc(:,jk) ; zv(:,1)=zvobc(:,jk) 
-            ELSE IF ( l_merid ) THEN ; zu(1,:)=zuobc(:,jk) ; zv(1,:)=zvobc(:,jk) ; ENDIF
-            ELSE
-               zu (:,:) = getvar(cf_ufil, cn_vozocrtx, jk, npiglo, npjglo, ktime=itime)
-               zv (:,:) = getvar(cf_vfil, cn_vomecrty, jk, npiglo, npjglo, ktime=itime)
-               IF (lheat) THEN
-                  zut(:,:) = getvar(cf_tfil, cn_vozout,   jk, npiglo, npjglo, ktime=itime)
-                  zvt(:,:) = getvar(cf_tfil, cn_vomevt,   jk, npiglo, npjglo, ktime=itime)
-                  zus(:,:) = getvar(cf_tfil, cn_vozous,   jk, npiglo, npjglo, ktime=itime)
-                  zvs(:,:) = getvar(cf_tfil, cn_vomevs,   jk, npiglo, npjglo, ktime=itime)
-               ENDIF
-            ENDIF
-
-            ! get e3u, e3v  at level jk
-            IF ( lfull ) THEN 
-               e3v(:,:) = e31d(jk)
-               e3u(:,:) = e31d(jk)
-            ELSE
-               e3v(:,:) = getvar(cn_fzgr, 'e3v_ps', jk, npiglo, npjglo, ldiom=.TRUE.)
-               e3u(:,:) = getvar(cn_fzgr, 'e3u_ps', jk, npiglo, npjglo, ldiom=.TRUE.)
-            ENDIF
-
-            dwku (:,:) = zu (:,:)*e2u(:,:)*e3u(:,:)*1.d0
-            dwkv (:,:) = zv (:,:)*e1v(:,:)*e3v(:,:)*1.d0
-
-            IF ( lpm ) THEN 
-               dwkup = 0.d0 ; dwkum = 0.d0
-               WHERE ( zu >= 0. ) 
-                  dwkup(:,:) = zu (:,:)*e2u(:,:)*e3u(:,:)*1.d0
-               ELSEWHERE 
-                  dwkum(:,:) = zu (:,:)*e2u(:,:)*e3u(:,:)*1.d0
-               END WHERE
-
-               dwkvp = 0.d0 ; dwkvm = 0.d0
-               WHERE ( zv >= 0. )
-                  dwkvp(:,:) = zv (:,:)*e1v(:,:)*e3v(:,:)*1.d0
-               ELSEWHERE
-                  dwkvm(:,:) = zv (:,:)*e1v(:,:)*e3v(:,:)*1.d0
-               END WHERE
-            ENDIF
-
-            IF ( lheat ) THEN
-               dwkut(:,:) = zut(:,:)*e2u(:,:)*e3u(:,:)*1.d0
-               dwkvt(:,:) = zvt(:,:)*e1v(:,:)*e3v(:,:)*1.d0
-               dwkus(:,:) = zus(:,:)*e2u(:,:)*e3u(:,:)*1.d0
-               dwkvs(:,:) = zvs(:,:)*e1v(:,:)*e3v(:,:)*1.d0
-            ENDIF
-
-            ! integrates vertically 
-            dtrpu (:,:,jclass) = dtrpu (:,:,jclass) + dwku (:,:)
-            dtrpv (:,:,jclass) = dtrpv (:,:,jclass) + dwkv (:,:)
-
-            IF ( lpm   ) THEN
-               dtrpup(:,:,jclass) = dtrpup(:,:,jclass) + dwkup(:,:)
-               dtrpvp(:,:,jclass) = dtrpvp(:,:,jclass) + dwkvp(:,:)
-               dtrpum(:,:,jclass) = dtrpum(:,:,jclass) + dwkum(:,:)
-               dtrpvm(:,:,jclass) = dtrpvm(:,:,jclass) + dwkvm(:,:)
-            ENDIF
-
-            IF ( lheat ) THEN
-               dtrput(:,:,jclass) = dtrput(:,:,jclass) + dwkut(:,:) * rau0*rcp
-               dtrpvt(:,:,jclass) = dtrpvt(:,:,jclass) + dwkvt(:,:) * rau0*rcp
-               dtrpus(:,:,jclass) = dtrpus(:,:,jclass) + dwkus(:,:)  
-               dtrpvs(:,:,jclass) = dtrpvs(:,:,jclass) + dwkvs(:,:)  
-            ENDIF
-
-         END DO  ! loop to next level
-      END DO    ! next class
-
-      OPEN(numout,FILE=cf_out)
-      ! also dump the results on txt files without any comments, some users  like it !
-      OPEN(numvtrp,FILE=cf_vtrp)
-      IF ( lheat ) THEN
-         OPEN(numhtrp,FILE=cf_htrp) ; OPEN(numstrp,FILE=cf_strp)
-      ENDIF
-
-      !################################################################################
-      ! enter interactive part 
-      !################################################################################
-      ! initialize all legs arrays and variable to 0 
-      dvolalleg = 0.d0 ; dvolallegcl(:) = 0.d0
-      IF ( lpm   ) THEN
-         dvolallegp = 0.d0 ; dvolallegclp(:) = 0.d0
-         dvolallegm = 0.d0 ; dvolallegclm(:) = 0.d0
-      ENDIF
-      IF ( lheat ) THEN
-         dheatalleg = 0.d0 ; dheatallegcl(:) = 0.d0
-         dsaltalleg = 0.d0 ; dsaltallegcl(:) = 0.d0
-      ENDIF
-      DO 
-         PRINT *, ' Give name of section (EOF to finish)'
-         READ(*,'(a)') cline
-         ii = 0
-         cldumt(:) = 'none'
-         ipos = index(cline,' ')
-         DO WHILE ( ipos > 1 )
-            ii = ii + 1
-            cldumt(ii) = cline(1:ipos - 1 )
-            cline = TRIM ( cline(ipos+1:) )
-            ipos  = index( cline,' ' )
-            IF ( ii >= 3 ) EXIT
-         END DO
-         csection = TRIM(cldumt(1) )
-         cvarname = TRIM(cldumt(2) )
-         clongname = TRIM(cldumt(3) )
-
-         IF (TRIM(csection) == 'EOF' ) THEN 
-            CLOSE(numout) ; CLOSE(numvtrp) 
-            IF ( lheat ) THEN 
-               CLOSE(numhtrp) ; CLOSE(numstrp) 
-            ENDIF
-            EXIT  ! infinite DO loop
-         ENDIF
-
-         ! create output fileset
-         CALL set_typvar( stypvar, csection, cvarname, clongname )
-         cf_outnc   = TRIM(csection)//'_transports.nc'
-         ncout      = create      (cf_outnc, 'none',    ikx,      iky, nclass, cdep='depth_class')
-         ierr       = createvar   (ncout,    stypvar,   nvarout,  ipk, id_varout, cdglobal=TRIM(cglobal) )
-         ierr       = putheadervar(ncout,    cf_ufil,   ikx, iky, nclass, pnavlon=rdum, pnavlat=rdum, pdep=rclass )
-         tim        = getvar1d    (cf_ufil,  cn_vtimec, npt     )
-         ierr       = putvar1d    (ncout,    tim,       npt, 'T')
-
-         PRINT *, ' Give iimin, iimax, ijmin, ijmax '
-         READ(*,*) iimin, iimax, ijmin, ijmax
-         !! Find the broken line between P1 (iimin,ijmin) and P2 (iimax, ijmax)
-         ! ... Initialization
-         ii0  = iimin ; ij0  = ijmin ; ii1  = iimax ;  ij1 = ijmax
-         rxi0 = ii0   ; ryj0 = ij0   ; rxi1 = ii1   ; ryj1 = ij1
-
-         ! compute direction of integrations and signs
-         !The transport across the section is the dot product of
-         !integral(line){(Mx,My)*dS} 
-         !Mx=integral(u*dz)  My=integral(v*dz)) and dS=(dy,-dx)}
-
-         !By defining the direction of the integration as 
-         idirx = SIGN(1,ii1-ii0) !positive to the east or if ii1=ii0
-         idiry = SIGN(1,ij1-ij0) !positive to the north or if ij1=ij0
-
-         !Then dS=(e2u*idiry,-e1v*idirx)
-         !This will produce the following sign convention:
-         !    West-to-est line (dx>0, dy=0)=> -My*dx (-ve for a northward flow)
-         !    South-to-north   (dy>0, dx=0)=>  Mx*dy (+ve for an eastward flow)
-         norm_u =  idiry
-         norm_v = -idirx
-
-         ! .. Compute equation:  ryj = aj rxi + bj [valid in the (i,j) plane]
-         IF ( (rxi1 -rxi0) /=  0 ) THEN
-            aj = (ryj1 - ryj0 ) / (rxi1 -rxi0)
-            bj = ryj0 - aj * rxi0
-         ELSE
-            aj = 10000.  ! flag value
-            bj = 0.
-         END IF
-
-         ! .. Compute equation:  rxi = ai ryj + bi [valid in the (i,j) plane]
-         IF ( (ryj1 -ryj0) /=  0 ) THEN
-            ai = (rxi1 - rxi0 ) / ( ryj1 -ryj0 )
-            bi = rxi0 - ai * ryj0
-         ELSE
-            ai = 10000. ! flag value
-            bi = 0.
-         END IF
-
-         ! ..  Compute the integer pathway: a succession of F points
-         np=0
-         ! .. Chose the strait line with the smallest slope
-         IF (ABS(aj) <=  1 ) THEN
-            ! ... Here, the best line is y(x)
-            ! ... If ii1 < ii0 swap points [ always describe section from left to right ]
-            IF (ii1 <  ii0 ) THEN
-               iitmp = ii0   ; ijtmp = ij0
-               ii0   = ii1   ; ij0   = ij1
-               ii1   = iitmp ; ij1   = ijtmp
-            END IF
-
-            ! iist,ijst is the grid offset to pass from F point to either U/V point
-            IF ( ij1 >= ij0 ) THEN     ! line heading NE
-               iist = 1 ; ijst = 1
-            ELSE                       ! line heading SE
-               iist = 1 ; ijst = 0
-            END IF
-
-            ! ... compute the nearest ji point on the line crossing at ji
-            DO ji=ii0, ii1
-               np=np+1
-               IF (np > jpseg) STOP 'np > jpseg !'
-               ij=NINT(aj*ji + bj )
-               yypt(np) = CMPLX(ji,ij)
-            END DO
-         ELSE
-            ! ... Here, the best line is x(y)
-            ! ... If ij1 < ij0 swap points [ always describe section from bottom to top ]
-            IF (ij1 <  ij0 ) THEN
-               iitmp = ii0   ; ijtmp = ij0
-               ii0   = ii1   ; ij0   = ij1
-               ii1   = iitmp ; ij1   = ijtmp
-            END IF
-
-            ! iist,ijst is the grid offset to pass from F point to either U/V point
-            IF ( ii1 >=  ii0 ) THEN
-               iist = 1 ; ijst = 1
-            ELSE
-               iist = 0 ; ijst = 1
-            END IF
-
-            ! ... compute the nearest ji point on the line crossing at jj
-            DO jj=ij0,ij1
-               np=np+1
-               IF (np > jpseg) STOP 'np > jpseg !'
-               ii=NINT(ai*jj + bi)
-               yypt(np) = CMPLX(ii,jj)
-            END DO
-         END IF
-
-         !!
-         !! Look for intermediate points to be added.
-         !  ..  The final positions are saved in rxx,ryy
-         rxx(1) = REAL(yypt(1))
-         ryy(1) = IMAG(yypt(1))
-         nn     = 1
-
-         DO jk=2,np
-            ! .. distance between 2 neighbour points
-            rd=ABS(yypt(jk)-yypt(jk-1))
-            ! .. intermediate points required if rd > 1
-            IF ( rd > 1 ) THEN
-               CALL interm_pt(yypt, jk, ai, bi, aj, bj, yypti)
-               nn=nn+1
-               IF (nn > jpseg) STOP 'nn>jpseg !'
-               rxx(nn) = REAL(yypti)
-               ryy(nn) = IMAG(yypti)
-            END IF
-            nn=nn+1
-            IF (nn > jpseg) STOP 'nn>jpseg !'
-            rxx(nn) = REAL(yypt(jk))
-            ryy(nn) = IMAG(yypt(jk))
-         END DO
-         ! record longitude and latitude of initial en endind point of the section
-         gla (1) = glamf( INT(rxx(1)),  INT(ryy(1))  ) 
-         gphi(1) = gphif( INT(rxx(1)),  INT(ryy(1))  ) 
-         gla (2) = glamf( INT(rxx(nn)), INT(ryy(nn)) ) 
-         gphi(2) = gphif( INT(rxx(nn)), INT(ryy(nn)) ) 
-
-         ! Now extract the transport through a section 
-         ! ... Check whether we need a u velocity or a v velocity
-         !   Think that the points are f-points and delimit either a U segment
-         !   or a V segment (iist and ijst are set in order to look for the correct
-         !   velocity point on the C-grid
-         PRINT *, TRIM(csection)
-         PRINT *, 'IMIN IMAX JMIN JMAX', iimin, iimax, ijmin, ijmax
-         WRITE(numout,*) '% Transport along a section by levels' ,TRIM(csection)
-         WRITE(numout,*) '% ---- IMIN IMAX JMIN JMAX'
-
-         dvoltrpbrtp  = 0.d0
-         dvoltrpbrtpp = 0.d0
-         dvoltrpbrtpm = 0.d0
-         dheatrpbrtp  = 0.d0
-         dsaltrpbrtp  = 0.d0
-         DO jclass=1,nclass
-            dvoltrpsum(jclass) = 0.d0
-            IF ( lpm   ) THEN
-               dvoltrpsump(jclass) = 0.d0
-               dvoltrpsumm(jclass) = 0.d0
-            ENDIF
-            IF ( lheat ) THEN
-               dheatrpsum(jclass) = 0.d0
-               dsaltrpsum(jclass) = 0.d0
-            ENDIF
-
-            ! segment jseg is a line between (rxx(jseg),ryy(jseg))  and (rxx(jseg+1),ryy(jseg+1))
-            DO jseg = 1, nn-1
-               ii0=rxx(jseg)
-               ij0=ryy(jseg)
-               IF ( rxx(jseg) ==  rxx(jseg+1) ) THEN    ! meridional segment, use U velocity
-                  dvoltrp(jseg)= dtrpu (ii0,ij0+ijst,jclass)*norm_u
-
-                  IF ( lpm   ) THEN 
-                     dvoltrpp(jseg)= dtrpup(ii0,ij0+ijst,jclass)*norm_u
-                     dvoltrpm(jseg)= dtrpum(ii0,ij0+ijst,jclass)*norm_u
-                  ENDIF
-
-                  IF ( lheat ) THEN
-                     dheatrp(jseg)= dtrput(ii0,ij0+ijst,jclass)*norm_u
-                     dsaltrp(jseg)= dtrpus(ii0,ij0+ijst,jclass)*norm_u
-                  ENDIF
-               ELSE IF ( ryy(jseg) == ryy(jseg+1) ) THEN ! zonal segment, use V velocity
-                  dvoltrp(jseg)=dtrpv (ii0+iist,ij0,jclass)*norm_v
-
-                  IF ( lpm   ) THEN 
-                     dvoltrpp(jseg)=dtrpvp(ii0+iist,ij0,jclass)*norm_v
-                     dvoltrpm(jseg)=dtrpvm(ii0+iist,ij0,jclass)*norm_v
-                  ENDIF
-
-                  IF ( lheat ) THEN
-                     dheatrp(jseg)=dtrpvt(ii0+iist,ij0,jclass)*norm_v
-                     dsaltrp(jseg)=dtrpvs(ii0+iist,ij0,jclass)*norm_v
-                  ENDIF
-               ELSE
-                  PRINT *,' ERROR :',  rxx(jseg),ryy(jseg),rxx(jseg+1),ryy(jseg+1) ! likely to never happen !
-               END IF
-               dvoltrpsum(jclass) = dvoltrpsum(jclass) + dvoltrp(jseg)
-               IF ( lpm   ) THEN 
-                  dvoltrpsump(jclass) = dvoltrpsump(jclass) + dvoltrpp(jseg)
-                  dvoltrpsumm(jclass) = dvoltrpsumm(jclass) + dvoltrpm(jseg)
-               ENDIF
-               IF ( lheat ) THEN
-                  dheatrpsum(jclass) = dheatrpsum(jclass) + dheatrp(jseg)
-                  dsaltrpsum(jclass) = dsaltrpsum(jclass) + dsaltrp(jseg)
-               ENDIF
-            END DO   ! next segment
-
-            ! Ascii outputs :      
-            IF (jclass == 1 ) THEN   ! print header when it is the first class
-               PRINT '(a,2f8.2,a,2f8.2)', 'FROM (LON LAT): ', gla(1),gphi(1),' TO (LON LAT) ', gla(2), gphi(2)
-               WRITE(numout,*)  '% ---- LONmin LATmin LONmax LATmax'
-               WRITE(numout,*)  '% Top(m)  Bottom(m)  MassTrans(Sv) HeatTrans(PW) SaltTrans(kt/s)'
-               WRITE(numout,*) 0 ,iimin, iimax, ijmin, ijmax
-               WRITE(numout,9003) 0. ,gla(1),gphi(1), gla(2), gphi(2)
-            ENDIF
-
-            PRINT *, gdepw(ilev0(jclass)), gdepw(ilev1(jclass)+1)
-            PRINT *, ' Mass transport : ', dvoltrpsum(jclass)/1.e6,' SV'
-            WRITE(numvtrp,'(e12.6)') dvoltrpsum(jclass) 
-            IF ( lpm   ) THEN
-               PRINT *, ' Positive Mass transport : ', dvoltrpsump(jclass)/1.e6,' SV'
-               PRINT *, ' Negative Mass transport : ', dvoltrpsumm(jclass)/1.e6,' SV'
-               WRITE(numout,9002) gdepw(ilev0(jclass)), gdepw(ilev1(jclass)+1), &
-                    &   dvoltrpsum(jclass)/1.e6, dvoltrpsump(jclass)/1.e6, dvoltrpsumm(jclass)/1.e6
-               WRITE(numvtrp,'(e12.6)') dvoltrpsump(jclass) 
-               WRITE(numvtrp,'(e12.6)') dvoltrpsumm(jclass) 
-            ENDIF
-
-            IF ( lheat ) THEN
-               PRINT *, ' Heat transport : ', dheatrpsum(jclass)/1.e15,' PW'
-               PRINT *, ' Salt transport : ', dsaltrpsum(jclass)/1.e6,' kT/s'
-               WRITE(numout,9002) gdepw(ilev0(jclass)), gdepw(ilev1(jclass)+1), &
-                    &   dvoltrpsum(jclass)/1.e6, dheatrpsum(jclass)/1.e15, dsaltrpsum(jclass)/1.e6
-               WRITE(numhtrp,'(e12.6)') dheatrpsum(jclass)
-               WRITE(numstrp,'(e12.6)') dsaltrpsum(jclass)
-            ELSE
-               IF ( .NOT. lpm ) WRITE(numout,9002) gdepw(ilev0(jclass)), gdepw(ilev1(jclass)+1), dvoltrpsum(jclass)/1.e6
-            ENDIF
-
-            ! netcdf output 
-            IF ( nclass > 1 ) THEN
-               rdum(1,1) = REAL(dvoltrpsum(jclass)/1.e6)
-               ierr = putvar(ncout,id_varout(ivtrpcl), rdum, jclass, 1, 1, ktime=itime ) 
-               IF ( lpm   ) THEN
-                  rdum(1,1) =  REAL(dvoltrpsump(jclass)/1.e6)
-                  ierr = putvar(ncout,id_varout(iptrpcl), rdum, jclass, 1, 1, ktime=itime ) 
-                  rdum(1,1) =  REAL(dvoltrpsumm(jclass)/1.e6)
-                  ierr = putvar(ncout,id_varout(imtrpcl), rdum, jclass, 1, 1, ktime=itime ) 
-               ENDIF
-               IF ( lheat ) THEN
-                  rdum(1,1) =  REAL(dheatrpsum(jclass)/1.e15)
-                  ierr = putvar(ncout,id_varout(ihtrpcl), rdum, jclass, 1, 1, ktime=itime ) 
-                  rdum(1,1) =  REAL(dsaltrpsum(jclass)/1.e6)
-                  ierr = putvar(ncout,id_varout(istrpcl), rdum, jclass, 1, 1, ktime=itime )
-               ENDIF
-            ENDIF
-            rdum(1,1) = REAL(gdepw(ilev0(jclass)))
-            ierr = putvar(ncout,id_varout(itop), rdum, jclass, 1, 1, ktime=itime )
-            rdum(1,1) = REAL(gdepw(ilev1(jclass)+1))
-            ierr = putvar(ncout,id_varout(ibot), rdum, jclass, 1, 1, ktime=itime )
-
-            dvoltrpbrtp = dvoltrpbrtp +  dvoltrpsum(jclass)
-            IF ( lpm  ) THEN
-               dvoltrpbrtpp = dvoltrpbrtpp + dvoltrpsump(jclass)
-               dvoltrpbrtpm = dvoltrpbrtpm + dvoltrpsumm(jclass)
-            ENDIF
-            IF ( lheat) THEN
-               dheatrpbrtp = dheatrpbrtp +  dheatrpsum(jclass)
-               dsaltrpbrtp = dsaltrpbrtp +  dsaltrpsum(jclass)
-            ENDIF
-            ! save sum over legs
-            dvolallegcl(jclass) = dvolallegcl(jclass) + dvoltrpsum(jclass)
-            IF ( lpm   ) THEN
-               dvolallegclp(jclass) = dvolallegclp(jclass) + dvoltrpsump(jclass)
-               dvolallegclm(jclass) = dvolallegclm(jclass) + dvoltrpsumm(jclass)
-            ENDIF
-            IF ( lheat ) THEN
-               dheatallegcl(jclass) = dheatallegcl(jclass) + dheatrpsum(jclass)
-               dsaltallegcl(jclass) = dsaltallegcl(jclass) + dsaltrpsum(jclass)
-            ENDIF
-         END DO ! next class
-         ! save sum over legs 
-         dvolalleg = dvolalleg + dvoltrpbrtp
-         IF ( lpm   ) THEN
-            dvolallegp = dvolallegp + dvoltrpbrtpp
-            dvolallegm = dvolallegm + dvoltrpbrtpm
-         ENDIF
-         IF ( lheat ) THEN
-            dheatalleg = dheatalleg + dheatrpbrtp
-            dsaltalleg = dsaltalleg + dsaltrpbrtp
-         ENDIF
-
-         IF ( nclass > 1 ) THEN 
-            PRINT *, ' ====================================================='
-            PRINT *, ' total Mass transport : ', dvoltrpbrtp/1.e6,' SV'
-            IF ( lpm   ) THEN
-               PRINT *, ' total positive transport : ', dvoltrpbrtpp/1.e6,' SV'
-               PRINT *, ' total negative transport : ', dvoltrpbrtpm/1.e6,' SV'
-            ENDIF
-            IF ( lheat ) THEN
-               PRINT *, ' total Heat transport : ', dheatrpbrtp/1.e15,' PW'
-               PRINT *, ' total Salt transport : ', dsaltrpbrtp/1.e6,' kT/s'
-            ENDIF
-         ENDIF
-         ierr = putvar0d(ncout,id_varout(ivtrp), REAL(dvoltrpbrtp/1.e6)        )
-         IF ( lpm   ) THEN
-            ierr = putvar0d(ncout,id_varout(iptrp), REAL(dvoltrpbrtpp/1.e6)    )
-            ierr = putvar0d(ncout,id_varout(imtrp), REAL(dvoltrpbrtpm/1.e6)    )
-         ENDIF
-         IF ( lheat ) THEN
-            ierr = putvar0d(ncout,id_varout(ihtrp), REAL(dheatrpbrtp/1.e15)    )
-            ierr = putvar0d(ncout,id_varout(istrp), REAL(dsaltrpbrtp/1.e6 )    )
-         ENDIF
-         ierr = putvar0d(ncout,id_varout(ilonmin), REAL(gla(1))  )
-         ierr = putvar0d(ncout,id_varout(ilonmax), REAL(gla(2))  )
-         ierr = putvar0d(ncout,id_varout(ilatmin), REAL(gphi(1)) )
-         ierr = putvar0d(ncout,id_varout(ilatmax), REAL(gphi(2)) )
-         ierr = closeout(ncout)
-      END DO ! infinite loop : gets out when input is EOF 
-
-
-      PRINT *,'   '
-      PRINT *,' Overall transports (sum of all legs done so far)'
-      DO jclass = 1, nclass
-         PRINT *, gdepw(ilev0(jclass)), gdepw(ilev1(jclass)+1)
-         PRINT *, ' Mass transport : ', dvolallegcl(jclass)/1.e6,' SV'
-         IF ( lpm   ) THEN
-            PRINT *, ' Positive Mass transport : ', dvolallegclp(jclass)/1.e6,' SV'
-            PRINT *, ' Negative Mass transport : ', dvolallegclm(jclass)/1.e6,' SV'
-         ENDIF
-
-         IF ( lheat ) THEN
-            PRINT *, ' Heat transport : ', dheatallegcl(jclass)/1.e15,' PW'
-            PRINT *, ' Salt transport : ', dsaltallegcl(jclass)/1.e6,' kT/s'
-         ENDIF
-      ENDDO
-
-      IF ( nclass > 1 ) THEN
-         PRINT *, ' ====================================================='
-         PRINT *, '    Mass transport      : ', dvolalleg/1.e6,' SV'
-         IF ( lpm ) THEN
-            PRINT *, '     positive transport : ', dvolallegp/1.e6,' SV'
-            PRINT *, '     negative transport : ', dvolallegm/1.e6,' SV'
-         ENDIF
-         IF ( lheat ) THEN
-            PRINT *, '     heat transport     : ', dheatalleg/1.e15,' PW'
-            PRINT *, '     salt transport     : ', dsaltalleg/1.e6,' kT/s'
-         ENDIF
-      ENDIF
-
-
-9000  FORMAT(I4,6(f9.3,f8.4))
-9001  FORMAT(I4,6(f9.2,f9.3))
-9002  FORMAT(f9.0,f9.0,f9.2,f9.2,f9.2)
-9003  FORMAT(f9.2,f9.2,f9.2,f9.2,f9.2)
-
-   CONTAINS
-      SUBROUTINE set_typvar ( sd_typvar, cdsection, cdvarname, cdlongname ) 
-         !!---------------------------------------------------------------------
-         !!                  ***  ROUTINE set_typvar  ***
-         !!
-         !! ** Purpose : Initialize typvar structure for netcdfoutput at a given section
-         !!
-         !! ** Method  : use varname longname to suffix variable name and attributes
-         !!              If varname and/or logname are not given (ie 'none') take
-         !!              standard default names
-         !!              Netcdf id for variables are passed as global variables
-         !!----------------------------------------------------------------------
-         TYPE(variable), DIMENSION(:), INTENT(out) :: sd_typvar        ! structure of output
-         CHARACTER(LEN=*),             INTENT(in ) :: cdsection
-         CHARACTER(LEN=*),             INTENT(in ) :: cdvarname
-         CHARACTER(LEN=*),             INTENT(in ) :: cdlongname
-         !!
-         INTEGER(KIND=4)                           :: ivar
-         CHARACTER(LEN=255)                        :: csuffixvarnam
-         CHARACTER(LEN=255)                        :: cprefixlongnam
-         !!----------------------------------------------------------------------
-         ! set suffixes according to variable/longname 
-         IF ( cdvarname /= 'none' ) THEN
-            csuffixvarnam = '_'//TRIM(cdvarname)
-         ELSE
-            csuffixvarnam = ''
-         ENDIF
-
-         IF ( cdlongname /= 'none' ) THEN
-            cprefixlongnam = TRIM(cdlongname)//'_'
-         ELSE
-            cprefixlongnam = ''
-         ENDIF
-
-         ! set common values
-         sd_typvar%rmissing_value=99999.
-         sd_typvar%scale_factor= 1.
-         sd_typvar%add_offset= 0.
-         sd_typvar%savelog10= 0.
-         sd_typvar%conline_operation='N/A'
-         sd_typvar%caxis='T'
-
-         ! set particular values for individual variables
-         ivar = 1  ; ivtrp = ivar
-         ipk(ivar) = 1
-         sd_typvar(ivar)%cname       = 'vtrp'//TRIM(csuffixvarnam)
-         sd_typvar(ivar)%cunits      = 'Sverdrup'
-         sd_typvar(ivar)%valid_min   = -500.
-         sd_typvar(ivar)%valid_max   =  500.
-         sd_typvar(ivar)%clong_name  = TRIM(cprefixlongnam)//'Volume_Transport'
-         sd_typvar(ivar)%cshort_name = 'vtrp'
-
-         IF ( lpm ) THEN 
-            ivar = ivar + 1 ; iptrp = ivar                                                  ;  imtrp = ivar+1
-            ipk(ivar) = 1                                                                   ;  ipk(ivar+1) = 1
-            sd_typvar(ivar)%cname       = 'ptrp'//TRIM(csuffixvarnam)                       ;  sd_typvar(ivar+1)%cname       = 'mtrp'//TRIM(csuffixvarnam)
-            sd_typvar(ivar)%cunits      = 'Sverdrup'                                        ;  sd_typvar(ivar+1)%cunits      = 'Sverdrup'
-            sd_typvar(ivar)%valid_min   = -500.                                             ;  sd_typvar(ivar+1)%valid_min   = -500.
-            sd_typvar(ivar)%valid_max   =  500.                                             ;  sd_typvar(ivar+1)%valid_max   =  500.
-            sd_typvar(ivar)%clong_name  = TRIM(cprefixlongnam)//'Positive_volume_transport' ;  sd_typvar(ivar+1)%clong_name  = TRIM(cprefixlongnam)//'Negative_volume_transport'
-            sd_typvar(ivar)%cshort_name = 'ptrp'                                            ;  sd_typvar(ivar+1)%cshort_name = 'mtrp'
-            ivar = ivar + 1
-         ENDIF
-
-         IF ( lheat ) THEN
-            ivar = ivar + 1 ; ihtrp = ivar                                                  ;  istrp = ivar+1
-            ipk(ivar) = 1                                                                   ;  ipk(ivar+1) = 1
-            sd_typvar(ivar)%cname       = 'htrp'//TRIM(csuffixvarnam)                       ;  sd_typvar(ivar+1)%cname       = 'strp'//TRIM(csuffixvarnam)
-            sd_typvar(ivar)%cunits      = 'PW'                                              ;  sd_typvar(ivar+1)%cunits      = 'kt/s'
-            sd_typvar(ivar)%valid_min   = -1000.                                            ;  sd_typvar(ivar+1)%valid_min   = -1000.
-            sd_typvar(ivar)%valid_max   =  1000.                                            ;  sd_typvar(ivar+1)%valid_max   =  1000.
-            sd_typvar(ivar)%clong_name  = TRIM(cprefixlongnam)//'Heat_Transport'            ;  sd_typvar(ivar+1)%clong_name  = TRIM(cprefixlongnam)//'Salt_Transport'
-            sd_typvar(ivar)%cshort_name = 'htrp'                                            ;  sd_typvar(ivar+1)%cshort_name = 'strp'
-            ivar = ivar + 1
-         ENDIF
-
-         ivar = ivar + 1 ; ilonmin = ivar                                                   ;  ilonmax = ivar+1
-         ipk(ivar) = 1                                                                      ;  ipk(ivar+1) = 1
-         sd_typvar(ivar)%cname       = 'lonmin'//TRIM(csuffixvarnam)                        ;  sd_typvar(ivar+1)%cname       = 'lonmax'//TRIM(csuffixvarnam)
-         sd_typvar(ivar)%cunits      = 'deg'                                                ;  sd_typvar(ivar+1)%cunits      = 'deg'
-         sd_typvar(ivar)%valid_min   = -180.                                                ;  sd_typvar(ivar+1)%valid_min   = -180.
-         sd_typvar(ivar)%valid_max   =  180.                                                ;  sd_typvar(ivar+1)%valid_max   =  180.
-         sd_typvar(ivar)%clong_name  = TRIM(cprefixlongnam)//'begin_longitude'              ;  sd_typvar(ivar+1)%clong_name  = TRIM(cprefixlongnam)//'end_longitude'
-         sd_typvar(ivar)%cshort_name = 'lonmin'                                             ;  sd_typvar(ivar+1)%cshort_name = 'lonmax'
-         ivar = ivar + 1
-
-         ivar = ivar + 1  ; ilatmin = ivar                                                  ;  ilatmax = ivar+1
-         ipk(ivar) = 1                                                                      ;  ipk(ivar+1) = 1
-         sd_typvar(ivar)%cname       = 'latmin'//TRIM(csuffixvarnam)                        ;  sd_typvar(ivar+1)%cname       = 'latmax'//TRIM(csuffixvarnam)
-         sd_typvar(ivar)%cunits      = 'deg'                                                ;  sd_typvar(ivar+1)%cunits      = 'deg'
-         sd_typvar(ivar)%valid_min   = -90.                                                 ;  sd_typvar(ivar+1)%valid_min   = -90.
-         sd_typvar(ivar)%valid_max   =  90.                                                 ;  sd_typvar(ivar+1)%valid_max   =  90.
-         sd_typvar(ivar)%clong_name  = TRIM(cprefixlongnam)//'begin_latitude'               ;  sd_typvar(ivar+1)%clong_name  = TRIM(cprefixlongnam)//'end_latitude'
-         sd_typvar(ivar)%cshort_name = 'latmin'                                             ;  sd_typvar(ivar+1)%cshort_name = 'latmax'
-         ivar = ivar + 1
-
-         ivar = ivar + 1  ; itop = ivar                                                     ;  ibot = ivar+1
-         ipk(ivar) = nclass                                                                 ;  ipk(ivar+1) = nclass
-         sd_typvar(ivar)%cname       = 'top'                                                ;  sd_typvar(ivar+1)%cname       = 'bottom'
-         sd_typvar(ivar)%cunits      = 'meters'                                             ;  sd_typvar(ivar+1)%cunits      = 'meters'
-         sd_typvar(ivar)%valid_min   = 0.                                                   ;  sd_typvar(ivar+1)%valid_min   = 0.
-         sd_typvar(ivar)%valid_max   = 10000.                                               ;  sd_typvar(ivar+1)%valid_max   = 10000.
-         sd_typvar(ivar)%clong_name  = 'class_min_depth'                                    ;  sd_typvar(ivar+1)%clong_name  = 'class_max_depth'
-         sd_typvar(ivar)%cshort_name = 'top'                                                ;  sd_typvar(ivar+1)%cshort_name = 'bottom'
-         ivar = ivar + 1
-
-         ivtrpcl = -1  ; ihtrpcl = -1 ; istrpcl = -1
-         IF ( nclass > 1 ) THEN  ! define additional variable for vertical profile of transport (per class)
-            ivar = ivar + 1  ; ivtrpcl = ivar
-            ipk(ivar) = nclass                      
-            sd_typvar(ivar)%cname       = 'vtrp_dep'//TRIM(csuffixvarnam) 
-            sd_typvar(ivar)%cunits      = 'SV'  
-            sd_typvar(ivar)%valid_min   = 0.       
-            sd_typvar(ivar)%valid_max   = 10000.  
-            sd_typvar(ivar)%clong_name  = TRIM(cprefixlongnam)//'Volume_Transport_per_class' 
-            sd_typvar(ivar)%cshort_name = 'vtrp_dep'            
-
-            IF ( lpm )  THEN
-               ivar = ivar + 1  ; iptrpcl = ivar                                             ;  imtrpcl = ivar+1
-               ipk(ivar) = nclass                                                            ;  ipk(ivar+1) = nclass
-               sd_typvar(ivar)%cname       = 'ptrp_dep'//TRIM(csuffixvarnam)                 ;  sd_typvar(ivar+1)%cname       = 'mtrp_dep'//TRIM(csuffixvarnam)
-               sd_typvar(ivar)%cunits      = 'SV'                                            ;  sd_typvar(ivar+1)%cunits      = 'SV'
-               sd_typvar(ivar)%valid_min   = -500.                                           ;  sd_typvar(ivar+1)%valid_min   = -500.
-               sd_typvar(ivar)%valid_max   =  500.                                           ;  sd_typvar(ivar+1)%valid_max   =  500.
-               sd_typvar(ivar)%clong_name  = TRIM(cprefixlongnam)//'Positive_trp_per_class'  ;  sd_typvar(ivar+1)%clong_name  = TRIM(cprefixlongnam)//'Negative_trp_per_class'
-               sd_typvar(ivar)%cshort_name = 'ptrp_dep'                                      ;  sd_typvar(ivar+1)%cshort_name = 'mtrp_dep'
-               ivar = ivar + 1
-            ENDIF
-
-            IF ( lheat ) THEN
-               ivar = ivar + 1  ; ihtrpcl = ivar                                              ;  istrpcl = ivar+1
-               ipk(ivar) = nclass                                                             ;  ipk(ivar+1) = nclass
-               sd_typvar(ivar)%cname       = 'htrp_dep'//TRIM(csuffixvarnam)                  ;  sd_typvar(ivar+1)%cname       = 'strp_dep'//TRIM(csuffixvarnam)
-               sd_typvar(ivar)%cunits      = 'PW'                                             ;  sd_typvar(ivar+1)%cunits      = 'kt/s'
-               sd_typvar(ivar)%valid_min   = -1000.                                           ;  sd_typvar(ivar+1)%valid_min   = -1000.
-               sd_typvar(ivar)%valid_max   =  1000.                                           ;  sd_typvar(ivar+1)%valid_max   =  1000.
-               sd_typvar(ivar)%clong_name  = TRIM(cprefixlongnam)//'Heat_Transport_per_class' ;  sd_typvar(ivar+1)%clong_name  = TRIM(cprefixlongnam)//'Salt_Transport_per_class'
-               sd_typvar(ivar)%cshort_name = 'htrp_dep'                                       ;  sd_typvar(ivar+1)%cshort_name = 'strp_dep'
-               ivar = ivar + 1
-            ENDIF
-         ENDIF
-
-      END SUBROUTINE set_typvar
-      SUBROUTINE interm_pt (ydpt, kk, pai, pbi, paj, pbj, ydpti)
-         !!---------------------------------------------------------------------
-         !!                  ***  ROUTINE nterm_pt  ***
-         !!
-         !! ** Purpose : Find the best intermediate points on a pathway.
-         !!
-         !! ** Method  : ydpt : complex vector of the positions of the nearest points
-         !!               kk  : current working index
-         !!          pai, pbi : slope and original ordinate of x(y)
-         !!          paj, pbj : slope and original ordinate of y(x)
-         !!             ydpti : Complex holding the position of intermediate point 
-         !!
-         !! ** Reference : 19/07/1999 : J.M. Molines in Clipper
-         !!----------------------------------------------------------------------
-         COMPLEX, DIMENSION(:), INTENT(in ) :: ydpt
-         COMPLEX,               INTENT(out) :: ydpti
-         REAL(KIND=4),          INTENT(in ) :: pai, pbi, paj, pbj
-         INTEGER(KIND=4),       INTENT(in ) :: kk
-         ! ... local
-         COMPLEX                            :: ylptmp1, ylptmp2
-         REAL(KIND=4)                       :: za0, zb0
-         REAL(KIND=4)                       :: za1, zb1
-         REAL(KIND=4)                       :: zd1, zd2
-         REAL(KIND=4)                       :: zxm, zym
-         REAL(KIND=4)                       :: zxp, zyp
-         !!----------------------------------------------------------------------
-         ! ... Determines whether we use y(x) or x(y):
-         IF (ABS(paj) <=  1) THEN
-            ! .....  use y(x)
-            ! ... possible intermediate points:
-            ylptmp1=ydpt(kk-1)+(1.,0.)                 ! M1 
-            ylptmp2=ydpt(kk-1)+CMPLX(0.,SIGN(1.,paj))  ! M2
-            !
-            ! ... M1 is the candidate point:
-            zxm=REAL(ylptmp1)
-            zym=IMAG(ylptmp1)
-            za0=paj
-            zb0=pbj
-            !
-            za1=-1./za0
-            zb1=zym - za1*zxm
-            ! ... P1 is the projection of M1 on the strait line
-            zxp=-(zb1-zb0)/(za1-za0)
-            zyp=za0*zxp + zb0
-            ! ... zd1 is the distance M1P1
-            zd1=(zxm-zxp)*(zxm-zxp) + (zym-zyp)*(zym-zyp)
-            !
-            ! ... M2 is the candidate point:
-            zxm=REAL(ylptmp2)
-            zym=IMAG(ylptmp2)
-            za1=-1./za0
-            zb1=zym - za1*zxm
-            ! ... P2 is the projection of M2 on the strait line
-            zxp=-(zb1-zb0)/(za1-za0)
-            zyp=za0*zxp + zb0
-            ! ... zd2 is the distance M2P2
-            zd2=(zxm-zxp)*(zxm-zxp) + (zym-zyp)*(zym-zyp)
-            ! ... chose the smallest (zd1,zd2)
-            IF (zd2 <=  zd1) THEN
-               ydpti=ylptmp2   ! use M2
-            ELSE
-               ydpti=ylptmp1   ! use M1
-            END IF
-            !
-         ELSE   
-            ! ...  use x(y)
-            ! ... possible intermediate points:
-            ylptmp1=ydpt(kk-1)+CMPLX(SIGN(1.,pai),0.)  ! M1
-            ylptmp2=ydpt(kk-1)+(0.,1.)                 ! M2
-            ! 
-            ! ... M1 is the candidate point:
-            zxm=REAL(ylptmp1)
-            zym=IMAG(ylptmp1)
-            za0=pai
-            zb0=pbi
-            !
-            za1=-1./za0
-            zb1=zxm - za1*zym
-            zyp=-(zb1-zb0)/(za1-za0)
-            zxp=za0*zyp + zb0
-            zd1=(zxm-zxp)*(zxm-zxp) + (zym-zyp)*(zym-zyp)
-            !
-            zxm=REAL(ylptmp2)
-            zym=IMAG(ylptmp2)
-            za1=-1./za0
-            zb1=zxm - za1*zym
-            zyp=-(zb1-zb0)/(za1-za0)
-            zxp=za0*zyp + zb0
-            zd2=(zxm-zxp)*(zxm-zxp) + (zym-zyp)*(zym-zyp)
-            IF (zd2 <=  zd1) THEN
-               ydpti=ylptmp2
-            ELSE
-               ydpti=ylptmp1
-            END IF
-         END IF
-      END SUBROUTINE interm_pt
-
-   END PROGRAM cdftransport
diff --git a/cdfvsig.f90 b/cdfvsig.f90
deleted file mode 100644
index c441c91..0000000
--- a/cdfvsig.f90
+++ /dev/null
@@ -1,292 +0,0 @@
-PROGRAM cdfvsig
-  !!======================================================================
-  !!                     ***  PROGRAM  cdfvsig  ***
-  !!=====================================================================
-  !!  ** Purpose : Compute the average values for the products 
-  !!               U.sig, V.sig, W.sig where sig is the potential density.
-  !!
-  !!  ** Method  : pass the CONFIG name and a series of tags as arguments.
-  !!               Tracers are interpolated on velocity points. The product
-  !!               is evaluated at velocity points.
-  !!
-  !! History : 2.1  : 11/2004  : J.M. Molines : Original code
-  !!           2.1  : 02/2010  : J.M. Molines : handle multiframes input files.
-  !!           3.0  : 04/2011  : J.M. Molines : Doctor norm + Lic.
-  !!----------------------------------------------------------------------
-  USE cdfio
-  USE eos
-  USE modcdfnames
-  USE modutils
-  !!----------------------------------------------------------------------
-  !! CDFTOOLS_3.0 , MEOM 2011
-  !! $Id$
-  !! Copyright (c) 2011, J.-M. Molines
-  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
-  !!----------------------------------------------------------------------
-  IMPLICIT NONE
-
-  INTEGER(KIND=4)                           :: ji, jj, jk, jt, jtt  ! dummy loop index
-  INTEGER(KIND=4)                           :: ierr                 ! working integer
-  INTEGER(KIND=4)                           :: narg, iargc          ! command line
-  INTEGER(KIND=4)                           :: npiglo,npjglo        ! size of the domain
-  INTEGER(KIND=4)                           :: npk, npt             ! size of the domain
-  INTEGER(KIND=4)                           :: ntframe              ! Cumul of time frame
-  INTEGER(KIND=4)                           :: ncoutu               ! ncid of output file
-  INTEGER(KIND=4)                           :: ncoutv               ! ncid of output file
-  INTEGER(KIND=4)                           :: ncoutw               ! ncid of output file
-  INTEGER(KIND=4), DIMENSION(3)             :: ipku, id_varoutu     ! level and varid's of output vars
-  INTEGER(KIND=4), DIMENSION(3)             :: ipkv, id_varoutv     ! level and varid's of output vars
-  INTEGER(KIND=4), DIMENSION(3)             :: ipkw, id_varoutw     ! level and varid's of output vars
-
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: ztemp,  zsal         ! Array to read a layer of data
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zu, zv, zw           ! Velocity component
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: ztempu, zsalu        ! Array to read a layer of data
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: ztempv, zsalv        ! Array to read a layer of data
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: ztempw, zsalw        ! Array to read a layer of data
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: umask,  vmask, wmask ! masks
-  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim                  ! time counter of individual files
-  REAL(KIND=4), DIMENSION(1)                :: timean               ! mean time
-
-  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dcumulus             ! Arrays for cumulated values
-  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dcumulvs             ! Arrays for cumulated values
-  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dcumulws             ! Arrays for cumulated values
-  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dcumulsu             ! Arrays for cumulated values
-  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dcumulsv             ! Arrays for cumulated values
-  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dcumulsw             ! Arrays for cumulated values
-  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dcumulu              ! Arrays for cumulated values
-  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dcumulv              ! Arrays for cumulated values
-  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dcumulw              ! Arrays for cumulated values
-  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dsigu                ! Array for sigma0 at u point
-  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dsigv                ! Array for sigma0 at v point
-  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dsigw                ! Array for sigma0 at w point
-  REAL(KIND=8)                              :: dtotal_time          ! cumulated time
-
-  CHARACTER(LEN=256)                        :: cf_tfil              ! TS file name
-  CHARACTER(LEN=256)                        :: cf_ufil              ! zonal velocity file
-  CHARACTER(LEN=256)                        :: cf_vfil              ! meridional velocity file
-  CHARACTER(LEN=256)                        :: cf_wfil              ! vertical velocity file
-  CHARACTER(LEN=256)                        :: cf_outu='usig.nc'    ! output file
-  CHARACTER(LEN=256)                        :: cf_outv='vsig.nc'    ! output file
-  CHARACTER(LEN=256)                        :: cf_outw='wsig.nc'    ! output file
-  CHARACTER(LEN=256)                        :: config               ! configuration name
-  CHARACTER(LEN=256)                        :: ctag                 ! current tag to work with               
-
-  TYPE (variable), DIMENSION(3)             :: stypvaru             ! structure for attributes
-  TYPE (variable), DIMENSION(3)             :: stypvarv             ! structure for attributes
-  TYPE (variable), DIMENSION(3)             :: stypvarw             ! structure for attributes
-
-  LOGICAL                                   :: lcaltmean            ! flag for mean time computation
-  !!----------------------------------------------------------------------
-  CALL ReadCdfNames()
-
-  !!  Read command line
-  narg= iargc()
-  IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfvsig CONFIG ''list_of_tags'' '
-     PRINT *,'     PURPOSE :'
-     PRINT *,'       Compute the time average values for second order products ' 
-     PRINT *,'       U.sig,  V.sig and W.sig.  Also save mean sigma-0 interpolated at'
-     PRINT *,'       velocity points, as well as mean velocity component, for further use.'
-     PRINT *,'      '
-     PRINT *,'     ARGUMENTS :'
-     PRINT *,'       CONFIG is the config name of a given experiment (eg ORCA025-G70)'
-     PRINT *,'            The program will look for gridT, gridU, gridV  and gridW files for' 
-     PRINT *,'            this config ( grid_T, grid_U, grid_V and grid_W are also accepted).'
-     PRINT *,'       list_of_tags : a list of time tags that will be used for time'
-     PRINT *,'            averaging. e.g. y2000m01d05 y2000m01d10 ...'
-     PRINT *,'      '
-     PRINT *,'     REQUIRED FILES :'
-     PRINT *,'        ',TRIM(cn_fmsk)
-     PRINT *,'      '
-     PRINT *,'     OUTPUT : '
-     PRINT *,'       netcdf file : ', TRIM(cf_outu),', ',TRIM(cf_outv),' and ', TRIM(cf_outw)
-     PRINT *,'       variables : vousig, vovsig, vowsig : mean product v x sigma-0 '
-     PRINT *,'                                            at velocity point.'
-     PRINT *,'                   vosigu, vosigv, vosigw : mean sigma-0 at velocity point.'
-     PRINT *,'                   ',TRIM(cn_vozocrtx),', ',TRIM(cn_vomecrty),', ',TRIM(cn_vovecrtz),' : mean velocity components.'
-     STOP
-  ENDIF
-
-  !! Initialisation from 1st file (all file are assume to have the same geometry)
-  CALL getarg (1, config)
-  CALL getarg (2, ctag  )
-
-  cf_tfil = SetFileName ( config, ctag, 'T')
-  cf_ufil = SetFileName ( config, ctag, 'U')
-  cf_vfil = SetFileName ( config, ctag, 'V')
-  cf_wfil = SetFileName ( config, ctag, 'W')
-
-  npiglo = getdim (cf_tfil,cn_x)
-  npjglo = getdim (cf_tfil,cn_y)
-  npk    = getdim (cf_tfil,cn_z)
-
-  ipku(:)= npk  ! all variables (input and output are 3D)
-  ipkv(:)= npk  !   "                     "
-  ipkw(:)= npk  !   "                     "
-
-  ! define output variables  U points
-  stypvaru%rmissing_value    = 0.
-  stypvaru%valid_min         = -100.
-  stypvaru%valid_max         = 100.
-  stypvaru%conline_operation = 'N/A'
-  stypvaru%caxis             = 'TZYX'
-
-  stypvaru(1)%cname          = 'vousig'           ; stypvaru(1)%cunits        = 'kg.m-2.s-1'
-  stypvaru(2)%cname          = 'vosigu'           ; stypvaru(2)%cunits        = 'kg.m-3'
-  stypvaru(3)%cname          =  cn_vozocrtx       ; stypvaru(3)%cunits        = 'm/s'
-
-  stypvaru(1)%clong_name     = 'Mean U x sigma0'  ; stypvaru(1)%cshort_name   = 'vousig'
-  stypvaru(2)%clong_name     = 'Mean sigma0 at U' ; stypvaru(2)%cshort_name   = 'vosigu'
-  stypvaru(3)%clong_name     = 'Mean zonal vel'   ; stypvaru(3)%cshort_name   = cn_vozocrtx
-
-  ! define output variables  V points
-  stypvarv%rmissing_value    = 0.
-  stypvarv%valid_min         = -100.
-  stypvarv%valid_max         = 100.
-  stypvarv%conline_operation = 'N/A'
-  stypvarv%caxis             = 'TZYX'
-
-  stypvarv(1)%cname          = 'vovsig'           ; stypvarv(1)%cunits        = 'kg.m-2.s-1'
-  stypvarv(2)%cname          = 'vosigv'           ; stypvarv(2)%cunits        = 'kg.m-3'
-  stypvarv(3)%cname          =  cn_vomecrty       ; stypvarv(3)%cunits        = 'm/s'
-
-  stypvarv(1)%clong_name     = 'Mean V x sigma0'  ; stypvarv(1)%cshort_name   = 'vovsig'
-  stypvarv(2)%clong_name     = 'Mean sigma0 at V' ; stypvarv(2)%cshort_name   = 'vosigv'
-  stypvarv(3)%clong_name     = 'Mean merid vel'   ; stypvarv(3)%cshort_name   = cn_vomecrty
-
-  ! define output variables  W points
-  stypvarw%rmissing_value    = 0.
-  stypvarw%valid_min         = -100.
-  stypvarw%valid_max         = 100.
-  stypvarw%conline_operation = 'N/A'
-  stypvarw%caxis             = 'TZYX'
-
-  stypvarw(1)%cname          = 'vowsig'           ; stypvarw(1)%cunits        = 'kg.m-2.s-1'
-  stypvarw(2)%cname          = 'vosigw'           ; stypvarw(2)%cunits        = 'kg.m-3'
-  stypvarw(3)%cname          =  cn_vovecrtz       ; stypvarw(3)%cunits        = 'm/s'
-
-  stypvarw(1)%clong_name     = 'Mean W x sigma0'  ; stypvarw(1)%cshort_name   = 'vowsig'
-  stypvarw(2)%clong_name     = 'Mean sigma0 at W' ; stypvarw(2)%cshort_name   = 'vosigw'
-  stypvarw(3)%clong_name     = 'Mean vert. vel'   ; stypvarw(3)%cshort_name   = cn_vovecrtz
-
-  PRINT *, 'npiglo =', npiglo
-  PRINT *, 'npjglo =', npjglo
-  PRINT *, 'npk    =', npk
-
-  ALLOCATE( dcumulus(npiglo,npjglo), dcumulvs(npiglo,npjglo), dcumulws(npiglo,npjglo) )
-  ALLOCATE( dcumulsu(npiglo,npjglo), dcumulsv(npiglo,npjglo), dcumulsw(npiglo,npjglo) )
-  ALLOCATE( dcumulu(npiglo,npjglo),  dcumulv(npiglo,npjglo),  dcumulw(npiglo,npjglo)  )
-  ALLOCATE( ztemp(npiglo,npjglo),    zsal(npiglo,npjglo)                              )
-  ALLOCATE( zu(npiglo,npjglo),       zv(npiglo,npjglo),       zw(npiglo,npjglo)       )
-  ALLOCATE( dsigu(npiglo,npjglo),    dsigv(npiglo,npjglo),    dsigw(npiglo,npjglo)    )
-  ALLOCATE( umask(npiglo,npjglo),    vmask(npiglo,npjglo),    wmask(npiglo,npjglo)    )
-
-  ! create output fileset
-  ncoutu = create      (cf_outu, cf_ufil,  npiglo, npjglo, npk        )
-  ierr   = createvar   (ncoutu,  stypvaru, 3,      ipku,   id_varoutu )
-  ierr   = putheadervar(ncoutu,  cf_ufil,  npiglo, npjglo, npk        )
-
-  ncoutv = create      (cf_outv, cf_vfil,  npiglo, npjglo, npk        )
-  ierr   = createvar   (ncoutv,  stypvarv, 3,      ipkv,   id_varoutv )
-  ierr   = putheadervar(ncoutv,  cf_vfil,  npiglo, npjglo, npk        )
-
-  ncoutw = create      (cf_outw, cf_wfil,  npiglo, npjglo, npk        )
-  ierr   = createvar   (ncoutw,  stypvarw, 3,      ipku,   id_varoutw )
-  ierr   = putheadervar(ncoutw,  cf_wfil,  npiglo, npjglo, npk        )
-
-  lcaltmean=.TRUE.
-  DO jk = 1, npk
-     PRINT *,'level ',jk
-     dcumulus(:,:) = 0.d0 ;  dcumulvs(:,:) = 0.d0 ; dcumulws(:,:) = 0.d0
-     dcumulsu(:,:) = 0.d0 ;  dcumulsv(:,:) = 0.d0 ; dcumulsw(:,:) = 0.d0
-     dcumulu(:,:)  = 0.d0 ;  dcumulv(:,:)  = 0.d0 ; dcumulw(:,:)  = 0.d0
-     dtotal_time   = 0.d0 ;  ntframe       = 0
-     
-     umask(:,:) = getvar(cn_fmsk, 'umask' , jk, npiglo, npjglo )
-     vmask(:,:) = getvar(cn_fmsk, 'vmask' , jk, npiglo, npjglo )
-     wmask(:,:) = getvar(cn_fmsk, 'tmask' , jk, npiglo, npjglo )
-
-     DO jt = 2, narg           ! loop on tags
-        CALL getarg (jt, ctag)
-        cf_tfil = SetFileName ( config, ctag, 'T' )
-        cf_ufil = SetFileName ( config, ctag, 'U' )
-        cf_vfil = SetFileName ( config, ctag, 'V' )
-        cf_wfil = SetFileName ( config, ctag, 'W' )
-
-        npt = getdim (cf_tfil, cn_t)
-        IF ( lcaltmean ) THEN
-           ALLOCATE ( tim(npt) )
-           tim = getvar1d(cf_tfil, cn_vtimec, npt)
-           dtotal_time = dtotal_time + SUM(tim(1:npt) )
-           DEALLOCATE( tim )
-        END IF
-
-        DO jtt = 1, npt  ! loop on time frame in a single file
-           ntframe    = ntframe+1
-           zu(:,:)    = getvar(cf_ufil, cn_vozocrtx, jk, npiglo, npjglo, ktime=jtt )
-           zv(:,:)    = getvar(cf_vfil, cn_vomecrty, jk, npiglo, npjglo, ktime=jtt )
-           zw(:,:)    = getvar(cf_wfil, cn_vovecrtz, jk, npiglo, npjglo, ktime=jtt )
-           ztemp(:,:) = getvar(cf_tfil, cn_votemper, jk, npiglo, npjglo, ktime=jtt )
-           zsal(:,:)  = getvar(cf_tfil, cn_vosaline, jk, npiglo, npjglo, ktime=jtt )
-
-           ! temperature at u point, v points
-           dsigu(:,:) = 0.d0  ; dsigv(:,:) = 0.d0
-           DO ji=1, npiglo-1
-              DO jj = 1, npjglo -1
-                 ztempu(ji,jj) = 0.5 * ( ztemp(ji,jj) + ztemp(ji+1,jj) )  ! temper at Upoint
-                 ztempv(ji,jj) = 0.5 * ( ztemp(ji,jj) + ztemp(ji,jj+1) )  ! temper at Vpoint
-                 zsalu(ji,jj)  = 0.5 * ( zsal(ji,jj)  +  zsal(ji+1,jj) )  ! sal at U point
-                 zsalv(ji,jj)  = 0.5 * ( zsal(ji,jj)  +  zsal(ji,jj+1) )  ! sal at v point
-              END DO
-           END DO
-           
-           dsigu(:,:) = sigma0(ztempu, zsalu, npiglo, npjglo) * umask(:,:)
-           dsigv(:,:) = sigma0(ztempv, zsalv, npiglo, npjglo) * vmask(:,:)
-
-           dcumulus(:,:) = dcumulus(:,:) + dsigu(:,:) * zu(:,:) * 1.d0
-           dcumulvs(:,:) = dcumulvs(:,:) + dsigv(:,:) * zv(:,:) * 1.d0
-           dcumulsu(:,:) = dcumulsu(:,:) + dsigu(:,:) * 1.d0
-           dcumulsv(:,:) = dcumulsv(:,:) + dsigv(:,:) * 1.d0
-           dcumulu(:,:)  = dcumulu(:,:)  + zu(:,:)    * 1.d0
-           dcumulv(:,:)  = dcumulv(:,:)  + zv(:,:)    * 1.d0
-          
-           IF ( jk > 1 ) THEN ! now wsig
-               ztempw(:,:)   = 0.5 * ( ztemp(:,:) + getvar(cf_tfil, cn_votemper, jk-1, npiglo, npjglo, ktime=jtt ))
-               zsalw(:,:)    = 0.5 * ( zsal(:,:)  + getvar(cf_tfil, cn_vosaline, jk-1, npiglo, npjglo, ktime=jtt ))
-               dsigw(:,:)    = sigma0(ztempw, zsalw, npiglo, npjglo) * wmask(:,:)
-               dcumulws(:,:) = dcumulws(:,:) + dsigw(:,:) * zw(:,:) * 1.d0
-               dcumulsw(:,:) = dcumulsw(:,:) + dsigw(:,:) * 1.d0
-               dcumulw(:,:)  = dcumulw(:,:)  + zw(:,:)    * 1.d0
-           ENDIF
-
-        END DO  !jtt
-     END DO  ! jt
-     ! finish with level jk ; compute mean (assume spval is 0 )
-     ierr = putvar(ncoutu, id_varoutu(1), SNGL(dcumulus(:,:)/ntframe), jk, npiglo, npjglo, kwght=ntframe )
-     ierr = putvar(ncoutu, id_varoutu(2), SNGL(dcumulsu(:,:)/ntframe), jk, npiglo, npjglo, kwght=ntframe )
-     ierr = putvar(ncoutu, id_varoutu(3), SNGL(dcumulu(:,:) /ntframe), jk, npiglo, npjglo, kwght=ntframe )
-
-     ierr = putvar(ncoutv, id_varoutv(1), SNGL(dcumulvs(:,:)/ntframe), jk, npiglo, npjglo, kwght=ntframe )
-     ierr = putvar(ncoutv, id_varoutv(2), SNGL(dcumulsv(:,:)/ntframe), jk, npiglo, npjglo, kwght=ntframe )
-     ierr = putvar(ncoutv, id_varoutv(3), SNGL(dcumulv(:,:) /ntframe), jk, npiglo, npjglo, kwght=ntframe )
-
-     ierr = putvar(ncoutw, id_varoutw(1), SNGL(dcumulws(:,:)/ntframe), jk, npiglo, npjglo, kwght=ntframe )
-     ierr = putvar(ncoutw, id_varoutw(2), SNGL(dcumulsw(:,:)/ntframe), jk, npiglo, npjglo, kwght=ntframe )
-     ierr = putvar(ncoutw, id_varoutw(3), SNGL(dcumulw(:,:) /ntframe), jk, npiglo, npjglo, kwght=ntframe )
-
-     IF ( lcaltmean )  THEN
-        timean(1) = dtotal_time/ntframe
-        ierr      = putvar1d(ncoutu, timean, 1, 'T')
-        ierr      = putvar1d(ncoutv, timean, 1, 'T')
-        ierr      = putvar1d(ncoutw, timean, 1, 'T')
-     END IF
-
-     lcaltmean = .FALSE. ! tmean already computed
-
-  END DO  ! loop to next level
-
-  ierr = closeout(ncoutu)
-  ierr = closeout(ncoutv)
-  ierr = closeout(ncoutw)
-
-END PROGRAM cdfvsig
diff --git a/src/.gitignore b/src/.gitignore
new file mode 100644
index 0000000..2d19fc7
--- /dev/null
+++ b/src/.gitignore
@@ -0,0 +1 @@
+*.html
diff --git a/Makefile b/src/Makefile
similarity index 64%
rename from Makefile
rename to src/Makefile
index f7e42d3..17f54aa 100644
--- a/Makefile
+++ b/src/Makefile
@@ -11,31 +11,34 @@
 
 include make.macro
 
-BINDIR = ./bin
+BINDIR = ../bin
 
 VPATH = $(BINDIR)
 
-EXEC = cdfmoy cdfmoyt cdfstd  cdfmoy_weighted cdfmoy_freq cdfvT \
-       cdfvsig cdfspeed cdfsum\
+EXEC = cdfmoy cdfmoyt cdfstd  cdfmoy_weighted cdfmoy_freq cdfvT cdfuv\
+       cdfvsig cdfspeed cdfsum cdfenstat\
        cdfmoyuvwt \
        cdfeke cdfrmsssh cdfstdevw cdfstdevts cdflinreg cdfimprovechk\
        cdfstats \
-       cdfbn2 cdfrichardson cdfsig0 cdfsigi cdfsiginsitu cdfbottomsig cdfbotpressure cdfspice\
-       cdfbottom cdfets cdfokubo-w cdfcurl cdfw cdfgeo-uv cdfmxl \
+       cdfbn2 cdfrichardson cdfsig0 cdfsigntr cdfsigi cdfsiginsitu cdfbottomsig cdfbotpressure cdfspice\
+       cdfbottom cdfets cdfokubo-w cdfcurl cdfdiv cdflap cdfw cdfgeo-uv cdfmxl \
        cdfrhoproj  cdfzisot cdfsigintegr cdfpvor \
        cdfmhst cdfvhst cdfvtrp cdftransport cdfvFWov \
-       cdfsigtrp cdftempvol-full\
-       cdfpsi cdfmoc  cdfmocsig cdfmean \
-       cdfheatc cdfzonalmean cdfhflx cdfwflx cdfbuoyflx\
-       cdfmxlheatc cdfmxlsaltc cdfmxlhcsc cdfvertmean cdfvint \
+       cdfsigtrp cdfsigtrp_broken cdftempvol-full\
+       cdfpsi cdfmoc  cdfmocsig cdfmean cdfdegradt cdfdegradu cdfdegradv cdfdegradw \
+       cdfheatc cdfzonalmean cdfzonalmeanvT cdfhflx cdfwflx cdfbuoyflx\
+       cdfmxlheatc cdfmxlsaltc cdfmxlhcsc cdfvertmean cdfvint cdffwc\
        cdfpendep cdfzonalsum cdficediags cdfzonalout\
        cdfprofile  cdfwhereij cdffindij cdfweight cdfmaxmoc cdfcensus cdfzoom cdfmax cdfprobe cdfinfo \
        cdf16bit cdfvita cdfvita-geo cdfconvert cdfflxconv cdfclip cdfsstconv cdfstrconv cdfbathy cdfvar \
+       cdfisf_fill cdfisf_forcing cdfisf_rnf cdfisf_poolchk \
+       cdficb_clim cdficb_diags \
        cdfcsp cdfcoloc cdfmltmask cdfstatcoord  cdfpolymask cdfsmooth cdfmkmask cdfdifmask\
+       cdfgradT cdfhgradb cdfeddyscale_pass1 cdfeddyscale \
        cdfkempemekeepe cdfbci cdfbti cdfnrjcomp cdfcofdis cdfsections cdfnorth_unfold cdfovide cdfmppini\
-       cdf2levitusgrid2d \
+       cdf_xtrac_brokenline cdf2levitusgrid2d  cdf2levitusgrid3d\
        cdfpsi_level cdfhdy cdfhdy3d cdffracinv  cdfmaskdmp cdfnan cdfscale cdfnamelist \
-       cdfisopsi cdf2matlab cdffixtime cdfgeostrophy cdfchgrid cdfcmp
+       cdfisopsi cdf2matlab cdffixtime cdfgeostrophy cdfchgrid cdfcmp 
 
 .PHONY: all help clean cleanexe install man installman
 
@@ -59,6 +62,12 @@ cdfmoy: cdfio.o   cdfmoy.f90
 cdfmoyt: cdfio.o   cdfmoyt.f90
 	$(F90) cdfmoyt.f90 -o $(BINDIR)/cdfmoyt cdfio.o modcdfnames.o  $(FFLAGS)
 
+cdfenstat: cdfio.o   cdfenstat.f90
+	$(F90) cdfenstat.f90 -o $(BINDIR)/cdfenstat cdfio.o modcdfnames.o  $(FFLAGS)
+
+cdfenstat2: cdfio.o   cdfenstat2.f90
+	$(F90) cdfenstat2.f90 -o $(BINDIR)/cdfenstat2 cdfio.o modcdfnames.o  $(FFLAGS)
+
 cdfmoy_freq: cdfio.o   cdfmoy_freq.f90
 	$(F90) cdfmoy_freq.f90 -o $(BINDIR)/cdfmoy_freq cdfio.o  modcdfnames.o $(FFLAGS)
 
@@ -86,12 +95,18 @@ cdfstdevts: cdfio.o  cdfstdevts.f90
 cdfvT: cdfio.o  modutils.o cdfvT.f90
 	$(F90) cdfvT.f90 -o $(BINDIR)/cdfvT cdfio.o modcdfnames.o modutils.o $(FFLAGS)
 
+cdfuv: cdfio.o  modutils.o cdfuv.f90
+	$(F90) cdfuv.f90 -o $(BINDIR)/cdfuv cdfio.o modcdfnames.o modutils.o $(FFLAGS)
+
 cdfvsig: cdfio.o eos.o modutils.o  cdfvsig.f90
-	$(F90) cdfvsig.f90 -o $(BINDIR)/cdfvsig cdfio.o eos.o modcdfnames.o modutils.o $(FFLAGS)
+	$(F90) $(OMP) cdfvsig.f90 -o $(BINDIR)/cdfvsig cdfio.o eos.o modcdfnames.o modutils.o $(FFLAGS)
 
 cdfspeed: cdfio.o  cdfspeed.f90
 	$(F90) cdfspeed.f90 -o $(BINDIR)/cdfspeed cdfio.o modcdfnames.o $(FFLAGS)
 
+cdfspeedlog: cdfio.o  cdfspeedlog.f90
+	$(F90) cdfspeedlog.f90 -o $(BINDIR)/cdfspeedlog cdfio.o modcdfnames.o $(FFLAGS)
+
 cdfimprovechk: cdfio.o  cdfimprovechk.f90
 	$(F90) cdfimprovechk.f90 -o $(BINDIR)/cdfimprovechk cdfio.o modcdfnames.o $(FFLAGS)
 
@@ -103,34 +118,37 @@ cdflinreg: cdfio.o  cdflinreg.f90
 
 ## Derived quantities programs
 cdfbn2: cdfio.o  eos.o  cdfbn2.f90
-	$(F90) cdfbn2.f90 -o $(BINDIR)/cdfbn2 cdfio.o eos.o modcdfnames.o $(FFLAGS)
+	$(F90) $(OMP) cdfbn2.f90 -o $(BINDIR)/cdfbn2 cdfio.o eos.o modcdfnames.o $(FFLAGS)
 
 cdfrichardson: cdfio.o  eos.o  cdfrichardson.f90
-	$(F90) cdfrichardson.f90 -o $(BINDIR)/cdfrichardson cdfio.o eos.o modcdfnames.o $(FFLAGS)
+	$(F90) $(OMP) cdfrichardson.f90 -o $(BINDIR)/cdfrichardson cdfio.o eos.o modcdfnames.o $(FFLAGS)
 
 cdfsig0: cdfio.o  eos.o  cdfsig0.f90
-	$(F90) cdfsig0.f90 -o $(BINDIR)/cdfsig0 cdfio.o eos.o modcdfnames.o  $(FFLAGS)
+	$(F90) $(OMP) cdfsig0.f90 -o $(BINDIR)/cdfsig0 cdfio.o eos.o modcdfnames.o  $(FFLAGS)
+
+cdfsigntr: cdfio.o  eos.o  cdfsigntr.f90
+	$(F90) $(OMP) cdfsigntr.f90 -o $(BINDIR)/cdfsigntr cdfio.o eos.o modcdfnames.o  $(FFLAGS)
 
 cdfspice: cdfio.o  eos.o  cdfspice.f90
-	$(F90) cdfspice.f90 -o $(BINDIR)/cdfspice cdfio.o modcdfnames.o  $(FFLAGS)
+	$(F90) $(OMP) cdfspice.f90 -o $(BINDIR)/cdfspice cdfio.o eos.o modcdfnames.o  $(FFLAGS)
 
 cdfsigi: cdfio.o  eos.o  cdfsigi.f90
-	$(F90) cdfsigi.f90 -o $(BINDIR)/cdfsigi cdfio.o eos.o  modcdfnames.o $(FFLAGS)
+	$(F90) $(OMP) cdfsigi.f90 -o $(BINDIR)/cdfsigi cdfio.o eos.o  modcdfnames.o $(FFLAGS)
 
 cdfsiginsitu: cdfio.o  eos.o  cdfsiginsitu.f90
-	$(F90) cdfsiginsitu.f90 -o $(BINDIR)/cdfsiginsitu cdfio.o eos.o modcdfnames.o $(FFLAGS)
+	$(F90) $(OMP) cdfsiginsitu.f90 -o $(BINDIR)/cdfsiginsitu cdfio.o eos.o modcdfnames.o $(FFLAGS)
 
 cdfbottomsig: cdfio.o  eos.o  cdfbottomsig.f90
-	$(F90) cdfbottomsig.f90 -o $(BINDIR)/cdfbottomsig cdfio.o eos.o modcdfnames.o $(FFLAGS)
+	$(F90) $(OMP) cdfbottomsig.f90 -o $(BINDIR)/cdfbottomsig cdfio.o eos.o modcdfnames.o $(FFLAGS)
 
 cdfbotpressure: cdfio.o  eos.o modutils.o  cdfbotpressure.f90
-	$(F90) cdfbotpressure.f90 -o $(BINDIR)/cdfbotpressure cdfio.o eos.o modcdfnames.o modutils.o $(FFLAGS)
+	$(F90) $(OMP) cdfbotpressure.f90 -o $(BINDIR)/cdfbotpressure cdfio.o eos.o modcdfnames.o modutils.o $(FFLAGS)
 
 cdfbottom: cdfio.o    cdfbottom.f90
 	$(F90) cdfbottom.f90 -o $(BINDIR)/cdfbottom cdfio.o  modcdfnames.o $(FFLAGS)
 
 cdfets: cdfio.o  eos.o  cdfets.f90
-	$(F90) cdfets.f90 -o $(BINDIR)/cdfets cdfio.o eos.o modcdfnames.o  $(FFLAGS)
+	$(F90) $(OMP) cdfets.f90 -o $(BINDIR)/cdfets cdfio.o eos.o modcdfnames.o  $(FFLAGS)
 
 cdfokubo-w: cdfio.o  cdfokubo-w.f90
 	$(F90) cdfokubo-w.f90 -o $(BINDIR)/cdfokubo-w cdfio.o modcdfnames.o $(FFLAGS)
@@ -141,6 +159,9 @@ cdfmsk: cdfio.o  cdfmsk.f90
 cdfmkmask: cdfio.o  cdfmkmask.f90
 	$(F90) cdfmkmask.f90 -o $(BINDIR)/cdfmkmask cdfio.o modcdfnames.o $(FFLAGS)
 
+cdfmeshmask: cdfio.o  cdfmeshmask.f90
+	$(F90) cdfmeshmask.f90 -o $(BINDIR)/cdfmeshmask cdfio.o modcdfnames.o $(FFLAGS)
+
 cdfmltmask: cdfio.o  cdfmltmask.f90
 	$(F90) cdfmltmask.f90 -o $(BINDIR)/cdfmltmask cdfio.o modcdfnames.o $(FFLAGS)
 
@@ -150,6 +171,18 @@ cdfdifmask: cdfio.o  cdfdifmask.f90
 cdfcurl: cdfio.o  cdfcurl.f90
 	$(F90) cdfcurl.f90 -o $(BINDIR)/cdfcurl cdfio.o modcdfnames.o $(FFLAGS)
 
+cdfdiv: cdfio.o  cdfdiv.f90
+	$(F90) cdfdiv.f90 -o $(BINDIR)/cdfdiv cdfio.o modcdfnames.o $(FFLAGS)
+
+cdflap: cdfio.o  cdflap.f90
+	$(F90) cdflap.f90 -o $(BINDIR)/cdflap cdfio.o modcdfnames.o $(FFLAGS)
+
+cdfeddyscale_pass1: cdfio.o  cdfeddyscale_pass1.f90
+	$(F90) cdfeddyscale_pass1.f90 -o $(BINDIR)/cdfeddyscale_pass1 cdfio.o modcdfnames.o $(FFLAGS)
+
+cdfeddyscale: cdfio.o  cdfeddyscale.f90
+	$(F90) cdfeddyscale.f90 -o $(BINDIR)/cdfeddyscale cdfio.o modcdfnames.o $(FFLAGS)
+
 cdfw: cdfio.o  cdfw.f90
 	$(F90) cdfw.f90 -o $(BINDIR)/cdfw cdfio.o modcdfnames.o $(FFLAGS)
 
@@ -157,13 +190,13 @@ cdfgeo-uv: cdfio.o  cdfgeo-uv.f90
 	$(F90) cdfgeo-uv.f90 -o $(BINDIR)/cdfgeo-uv cdfio.o modcdfnames.o $(FFLAGS)
 
 cdfgeostrophy: cdfio.o eos.o cdfgeostrophy.f90
-	$(F90) cdfgeostrophy.f90 -o $(BINDIR)/cdfgeostrophy cdfio.o eos.o modcdfnames.o $(FFLAGS)
+	$(F90) $(OMP) cdfgeostrophy.f90 -o $(BINDIR)/cdfgeostrophy cdfio.o eos.o modcdfnames.o $(FFLAGS)
 
 cdfmxl: cdfio.o eos.o  cdfmxl.f90
-	$(F90) cdfmxl.f90 -o $(BINDIR)/cdfmxl cdfio.o eos.o modcdfnames.o $(FFLAGS)
+	$(F90) $(OMP) cdfmxl.f90 -o $(BINDIR)/cdfmxl cdfio.o eos.o modcdfnames.o $(FFLAGS)
 
 cdfrhoproj: cdfio.o  cdfrhoproj.f90
-	$(F90) cdfrhoproj.f90 -o $(BINDIR)/cdfrhoproj cdfio.o modcdfnames.o  $(FFLAGS) 
+	$(F90) $(OMP) cdfrhoproj.f90 -o $(BINDIR)/cdfrhoproj cdfio.o modcdfnames.o  $(FFLAGS) 
 
 cdfzisot: cdfio.o  cdfzisot.f90
 	$(F90) cdfzisot.f90 -o $(BINDIR)/cdfzisot cdfio.o modcdfnames.o  $(FFLAGS) 
@@ -172,10 +205,16 @@ cdfsigintegr: cdfio.o  modutils.o cdfsigintegr.f90
 	$(F90) cdfsigintegr.f90 -o $(BINDIR)/cdfsigintegr cdfio.o modcdfnames.o modutils.o  $(FFLAGS) 
 
 cdfisopsi: cdfio.o eos.o cdfisopsi.f90
-	$(F90) cdfisopsi.f90 -o $(BINDIR)/cdfisopsi cdfio.o eos.o modcdfnames.o  $(FFLAGS) 
+	$(F90) $(OMP) cdfisopsi.f90 -o $(BINDIR)/cdfisopsi cdfio.o eos.o modcdfnames.o  $(FFLAGS) 
 
 cdfpvor: eos.o cdfio.o  cdfpvor.f90
-	$(F90) cdfpvor.f90 -o $(BINDIR)/cdfpvor cdfio.o eos.o modcdfnames.o  $(FFLAGS) 
+	$(F90) $(OMP) cdfpvor.f90 -o $(BINDIR)/cdfpvor cdfio.o eos.o modcdfnames.o  $(FFLAGS) 
+
+cdfgradT: cdfio.o  cdfgradT.f90
+	$(F90) cdfgradT.f90 -o $(BINDIR)/cdfgradT cdfio.o  modcdfnames.o  $(FFLAGS) 
+
+cdfhgradb: cdfio.o  eos.o cdfhgradb.f90
+	$(F90) cdfhgradb.f90 -o $(BINDIR)/cdfhgradb cdfio.o  eos.o modcdfnames.o  $(FFLAGS) 
 
 cdfkempemekeepe: cdfio.o  cdfkempemekeepe.f90
 	$(F90) cdfkempemekeepe.f90 -o $(BINDIR)/cdfkempemekeepe cdfio.o  modcdfnames.o $(FFLAGS) 
@@ -190,13 +229,13 @@ cdfnrjcomp: cdfio.o  cdfnrjcomp.f90
 	$(F90) cdfnrjcomp.f90 -o $(BINDIR)/cdfnrjcomp cdfio.o modcdfnames.o $(FFLAGS) 
 
 cdfhdy: cdfio.o  eos.o  cdfhdy.f90
-	$(F90) cdfhdy.f90 -o $(BINDIR)/cdfhdy cdfio.o eos.o modcdfnames.o $(FFLAGS)
+	$(F90) $(OMP) cdfhdy.f90 -o $(BINDIR)/cdfhdy cdfio.o eos.o modcdfnames.o $(FFLAGS)
 
 cdfhdy3d: cdfio.o  eos.o  cdfhdy3d.f90
-	$(F90) cdfhdy3d.f90 -o $(BINDIR)/cdfhdy3d cdfio.o eos.o  modcdfnames.o $(FFLAGS)
+	$(F90) $(OMP) cdfhdy3d.f90 -o $(BINDIR)/cdfhdy3d cdfio.o eos.o  modcdfnames.o $(FFLAGS)
 
 cdfmaskdmp: cdfio.o  eos.o  cdfmaskdmp.f90
-	$(F90) cdfmaskdmp.f90 -o $(BINDIR)/cdfmaskdmp cdfio.o eos.o modcdfnames.o  $(FFLAGS)
+	$(F90) $(OMP) cdfmaskdmp.f90 -o $(BINDIR)/cdfmaskdmp cdfio.o eos.o modcdfnames.o  $(FFLAGS)
 
 ## Transport programs
 cdfmhst: cdfio.o  cdfmhst.f90
@@ -221,29 +260,44 @@ cdfvFWov: cdfio.o  modutils.o cdfvFWov.f90
 	$(F90) cdfvFWov.f90 -o $(BINDIR)/cdfvFWov cdfio.o modcdfnames.o modutils.o $(FFLAGS)
 
 cdfsigtrp: cdfio.o eos.o  modutils.o cdfsigtrp.f90 
-	$(F90)  cdfsigtrp.f90 -o $(BINDIR)/cdfsigtrp cdfio.o eos.o modcdfnames.o modutils.o  $(FFLAGS)
+	$(F90)  $(OMP) cdfsigtrp.f90 -o $(BINDIR)/cdfsigtrp cdfio.o eos.o modcdfnames.o modutils.o  $(FFLAGS)
+
+cdfsigtrp_broken: cdfio.o eos.o  modutils.o cdfsigtrp_broken.f90 
+	$(F90)  $(OMP) cdfsigtrp_broken.f90 -o $(BINDIR)/cdfsigtrp_broken cdfio.o eos.o modcdfnames.o modutils.o  $(FFLAGS)
 
 cdftransig_xy3d: cdfio.o eos.o  modutils.o cdftransig_xy3d.f90
-	$(F90)  cdftransig_xy3d.f90 -o $(BINDIR)/cdftransig_xy3d cdfio.o eos.o modcdfnames.o modutils.o  $(FFLAGS)
+	$(F90)  $(OMP) cdftransig_xy3d.f90 -o $(BINDIR)/cdftransig_xy3d cdfio.o eos.o modcdfnames.o modutils.o  $(FFLAGS)
 
 cdftempvol-full: cdfio.o  cdftempvol-full.f90
 	$(F90) cdftempvol-full.f90 -o $(BINDIR)/cdftempvol-full cdfio.o modcdfnames.o  $(FFLAGS)
 
 cdfmoc: cdfio.o  eos.o cdftools.o cdfmoc.f90
-	$(F90) cdfmoc.f90 -o $(BINDIR)/cdfmoc cdfio.o eos.o modcdfnames.o cdftools.o $(FFLAGS)
+	$(F90) $(OMP) cdfmoc.f90 -o $(BINDIR)/cdfmoc cdfio.o eos.o modcdfnames.o cdftools.o $(FFLAGS)
 
 cdfmht_gsop: cdfio.o eos.o  cdfmht_gsop.f90
-	$(F90) cdfmht_gsop.f90 -o $(BINDIR)/cdfmht_gsop cdfio.o eos.o modcdfnames.o $(FFLAGS)
+	$(F90) $(OMP) cdfmht_gsop.f90 -o $(BINDIR)/cdfmht_gsop cdfio.o eos.o modcdfnames.o $(FFLAGS)
 
 cdfmoc_rapid_26N_r8_ORCA025: cdfio.o eos.o  cdfmoc_rapid_26N_r8_ORCA025.f90
-	$(F90) cdfmoc_rapid_26N_r8_ORCA025.f90 -o $(BINDIR)/cdfmoc_rapid_26N_r8_ORCA025 cdfio.o eos.o $(FFLAGS)
+	$(F90) $(OMP) cdfmoc_rapid_26N_r8_ORCA025.f90 -o $(BINDIR)/cdfmoc_rapid_26N_r8_ORCA025 cdfio.o eos.o $(FFLAGS)
 
 cdfmocsig: cdfio.o eos.o modutils.o  cdfmocsig.f90 
-	$(F90) cdfmocsig.f90 -o $(BINDIR)/cdfmocsig cdfio.o eos.o modcdfnames.o modutils.o $(FFLAGS)
+	$(F90) $(OMP) cdfmocsig.f90 -o $(BINDIR)/cdfmocsig cdfio.o eos.o modcdfnames.o modutils.o $(FFLAGS)
 
 cdfmean: cdfio.o  cdfmean.f90
 	$(F90) cdfmean.f90 -o $(BINDIR)/cdfmean cdfio.o modcdfnames.o $(FFLAGS)
 
+cdfdegradt: cdfio.o  cdfdegradt.f90
+	$(F90) cdfdegradt.f90 -o $(BINDIR)/cdfdegradt cdfio.o modcdfnames.o $(FFLAGS)
+
+cdfdegradu: cdfio.o  cdfdegradu.f90
+	$(F90) cdfdegradu.f90 -o $(BINDIR)/cdfdegradu cdfio.o modcdfnames.o $(FFLAGS)
+
+cdfdegradv: cdfio.o  cdfdegradv.f90
+	$(F90) cdfdegradv.f90 -o $(BINDIR)/cdfdegradv cdfio.o modcdfnames.o $(FFLAGS)
+
+cdfdegradw: cdfio.o  cdfdegradw.f90
+	$(F90) cdfdegradw.f90 -o $(BINDIR)/cdfdegradw cdfio.o modcdfnames.o $(FFLAGS)
+
 cdfsum: cdfio.o  cdfsum.f90
 	$(F90) cdfsum.f90 -o $(BINDIR)/cdfsum cdfio.o modcdfnames.o $(FFLAGS)
 
@@ -253,6 +307,9 @@ cdfvertmean: cdfio.o  modutils.o cdfvertmean.f90
 cdfvint: cdfio.o  modutils.o cdfvint.f90
 	$(F90) cdfvint.f90 -o $(BINDIR)/cdfvint cdfio.o modcdfnames.o modutils.o $(FFLAGS)
 
+cdffwc: cdfio.o  modutils.o cdffwc.f90
+	$(F90) cdffwc.f90 -o $(BINDIR)/cdffwc cdfio.o modcdfnames.o modutils.o $(FFLAGS)
+
 cdfheatc: cdfio.o modutils.o cdfheatc.f90
 	$(F90) cdfheatc.f90 -o $(BINDIR)/cdfheatc cdfio.o modcdfnames.o modutils.o $(FFLAGS)
 
@@ -263,13 +320,19 @@ cdfmxlsaltc: cdfio.o  modutils.o cdfmxlsaltc.f90
 	$(F90) cdfmxlsaltc.f90 -o $(BINDIR)/cdfmxlsaltc cdfio.o modcdfnames.o modutils.o $(FFLAGS)
 
 cdfmxlhcsc: cdfio.o  eos.o cdfmxlhcsc.f90
-	$(F90) cdfmxlhcsc.f90 -o $(BINDIR)/cdfmxlhcsc cdfio.o eos.o modcdfnames.o $(FFLAGS)
+	$(F90) $(OMP) cdfmxlhcsc.f90 -o $(BINDIR)/cdfmxlhcsc cdfio.o eos.o modcdfnames.o $(FFLAGS)
 
 cdficediags: cdfio.o  cdficediags.f90
 	$(F90) cdficediags.f90 -o $(BINDIR)/cdficediags cdfio.o modcdfnames.o $(FFLAGS)
 
 cdfzonalmean: cdfio.o  cdfzonalmean.f90
-	$(F90) cdfzonalmean.f90 -o $(BINDIR)/cdfzonalmean cdfio.o modcdfnames.o $(FFLAGS) 
+	$(F90) $(OMP) cdfzonalmean.f90 -o $(BINDIR)/cdfzonalmean cdfio.o modcdfnames.o $(FFLAGS) 
+
+cdfzonalmeanvT: cdfio.o  modutils.o  cdfzonalmeanvT.f90
+	$(F90) cdfzonalmeanvT.f90 -o $(BINDIR)/cdfzonalmeanvT cdfio.o modcdfnames.o modutils.o $(FFLAGS) 
+
+cdfzonalmeanvT2: cdfio.o  modutils.o  cdfzonalmeanvT2.f90
+	$(F90) cdfzonalmeanvT2.f90 -o $(BINDIR)/cdfzonalmeanvT2 cdfio.o modcdfnames.o modutils.o $(FFLAGS) 
 
 cdfzonalsum: cdfio.o  cdfzonalsum.f90
 	$(F90) cdfzonalsum.f90 -o $(BINDIR)/cdfzonalsum cdfio.o modcdfnames.o $(FFLAGS) 
@@ -284,7 +347,7 @@ cdfwflx: cdfio.o  cdfwflx.f90
 	$(F90) cdfwflx.f90 -o $(BINDIR)/cdfwflx cdfio.o modcdfnames.o $(FFLAGS)
 
 cdfbuoyflx: cdfio.o  eos.o cdfbuoyflx.f90
-	$(F90) cdfbuoyflx.f90 -o $(BINDIR)/cdfbuoyflx cdfio.o eos.o modcdfnames.o $(FFLAGS)
+	$(F90) $(OMP) cdfbuoyflx.f90 -o $(BINDIR)/cdfbuoyflx cdfio.o eos.o modcdfnames.o $(FFLAGS)
 
 ## Extracting tools, information tools
 cdfprofile: cdfio.o  cdfprofile.f90
@@ -320,14 +383,26 @@ cdfcoloc3: cdfio.o  cdfcoloc3.f90
 cdf2levitusgrid2d: cdfio.o cdftools.o modutils.o cdf2levitusgrid2d.f90
 	$(F90) cdf2levitusgrid2d.f90  -o $(BINDIR)/cdf2levitusgrid2d  cdfio.o modcdfnames.o cdftools.o modutils.o $(FFLAGS)
 
+cdf2levitusgrid3d: cdfio.o cdftools.o modutils.o cdf2levitusgrid3d.f90
+	$(F90) cdf2levitusgrid3d.f90  -o $(BINDIR)/cdf2levitusgrid3d  cdfio.o modcdfnames.o cdftools.o modutils.o $(FFLAGS)
+
+cdf025to05: cdfio.o  cdf025to05.f90
+	$(F90) cdf025to05.f90  -o $(BINDIR)/cdf025to05 cdfio.o modcdfnames.o $(FFLAGS)
+
+cdfrnf025to05: cdfio.o  cdfrnf025to05.f90
+	$(F90) cdfrnf025to05.f90  -o $(BINDIR)/cdfrnf025to05 cdfio.o modcdfnames.o $(FFLAGS)
+
 cdfstatcoord: cdfio.o  cdfstatcoord.f90
 	$(F90) cdfstatcoord.f90  -o $(BINDIR)/cdfstatcoord cdfio.o modcdfnames.o $(FFLAGS)
 
+cdfpdf: cdfio.o  modutils.o cdfpdf.f90
+	$(F90) cdfpdf.f90  -o $(BINDIR)/cdfpdf cdfio.o modutils.o modcdfnames.o $(FFLAGS)
+
 cdfmaxmoc: cdfio.o cdfmaxmoc.f90 
 	$(F90) cdfmaxmoc.f90  -o $(BINDIR)/cdfmaxmoc cdfio.o modcdfnames.o $(FFLAGS)
 
 cdfcensus: cdfio.o eos.o cdfcensus.f90
-	$(F90) cdfcensus.f90  -o $(BINDIR)/cdfcensus cdfio.o eos.o modcdfnames.o $(FFLAGS)
+	$(F90) $(OMP) cdfcensus.f90  -o $(BINDIR)/cdfcensus cdfio.o eos.o modcdfnames.o $(FFLAGS)
 
 cdfzoom: cdfio.o  cdfzoom.f90
 	$(F90) cdfzoom.f90  -o $(BINDIR)/cdfzoom cdfio.o modcdfnames.o $(FFLAGS)
@@ -344,8 +419,8 @@ cdfinfo: cdfio.o  cdfinfo.f90
 cdfclip: cdfio.o  cdfclip.f90
 	$(F90) cdfclip.f90  -o $(BINDIR)/cdfclip cdfio.o modcdfnames.o $(FFLAGS)
 
-cdfsmooth: cdfio.o  cdfsmooth.f90
-	$(F90) cdfsmooth.f90  -o $(BINDIR)/cdfsmooth cdfio.o modcdfnames.o $(FFLAGS)
+cdfsmooth: cdfio.o  modutils.o cdfsmooth.f90
+	$(F90) cdfsmooth.f90  -o $(BINDIR)/cdfsmooth cdfio.o modutils.o modcdfnames.o $(FFLAGS)
 
 cdfpendep: cdfio.o  cdfpendep.f90
 	$(F90) cdfpendep.f90  -o $(BINDIR)/cdfpendep cdfio.o modcdfnames.o $(FFLAGS)
@@ -408,9 +483,30 @@ cdfnorth_unfold: cdfio.o cdfnorth_unfold.f90
 cdfpolymask: cdfio.o modpoly.o cdfpolymask.f90
 	$(F90)   cdfpolymask.f90  -o $(BINDIR)/cdfpolymask cdfio.o modpoly.o modcdfnames.o $(FFLAGS)
 
+cdfisf_fill: cdfio.o  modutils.o cdfisf_fill.f90
+	$(F90)   cdfisf_fill.f90  -o $(BINDIR)/cdfisf_fill cdfio.o modutils.o modcdfnames.o $(FFLAGS)
+
+cdfisf_forcing: cdfio.o  cdfisf_forcing.f90
+	$(F90)   cdfisf_forcing.f90  -o $(BINDIR)/cdfisf_forcing cdfio.o modcdfnames.o $(FFLAGS)
+
+cdfisf_rnf: cdfio.o  cdfisf_rnf.f90
+	$(F90)   cdfisf_rnf.f90  -o $(BINDIR)/cdfisf_rnf cdfio.o modcdfnames.o $(FFLAGS)
+
+cdfisf_poolchk: cdfio.o  modutils.o cdfisf_poolchk.f90
+	$(F90)   cdfisf_poolchk.f90  -o $(BINDIR)/cdfisf_poolchk cdfio.o modutils.o modcdfnames.o $(FFLAGS)
+
+cdficb_clim: cdfio.o  cdficb_clim.f90
+	$(F90) cdficb_clim.f90 -o $(BINDIR)/cdficb_clim cdfio.o modcdfnames.o $(FFLAGS)
+
+cdficb_diags: cdfio.o  cdficb_diags.f90
+	$(F90) cdficb_diags.f90 -o $(BINDIR)/cdficb_diags cdfio.o modcdfnames.o $(FFLAGS)
+
 cdfovide: cdfio.o  cdfovide.f90
 	$(F90) cdfovide.f90  -o $(BINDIR)/cdfovide cdfio.o modcdfnames.o $(FFLAGS)
 
+cdf_xtrac_brokenline: cdfio.o  modcdfnames.o cdftools.o  cdf_xtrac_brokenline.f90
+	$(F90)  cdf_xtrac_brokenline.f90  -o $(BINDIR)/cdf_xtrac_brokenline cdfio.o cdftools.o modcdfnames.o $(FFLAGS)
+
 cdfmppini: cdfio.o  cdfmppini.f90
 	$(F90)  cdfmppini.f90  -o $(BINDIR)/cdfmppini cdfio.o modcdfnames.o $(FFLAGS)
 
@@ -420,23 +516,22 @@ cdffixtime: cdfio.o  cdffixtime.f90
 cdfnamelist: modcdfnames.o  cdfnamelist.f90
 	$(F90)  cdfnamelist.f90  -o $(BINDIR)/cdfnamelist  modcdfnames.o $(FFLAGS) $(FDATE_FLAG)
 
-cdfchgrid: cdfio.o cdfchgrid.f90
-	$(F90) cdfchgrid.f90  -o $(BINDIR)/cdfchgrid cdfio.o modcdfnames.o $(FFLAGS)
+cdfchgrid: cdfio.o modutils.o cdfchgrid.f90
+	$(F90) cdfchgrid.f90  -o $(BINDIR)/cdfchgrid cdfio.o modcdfnames.o modutils.o $(FFLAGS)
 
 cdfcmp: cdfio.o cdfcmp.f90
 	$(F90) cdfcmp.f90  -o $(BINDIR)/cdfcmp cdfio.o modcdfnames.o $(FFLAGS)
 
-# OLD bimg/dimg stuff: use by the trpsig monitoring....
 cdfsections: eos.o cdfsections.f90
-	$(F90) cdfsections.f90  -o $(BINDIR)/cdfsections eos.o modcdfnames.o $(FFLAGS)
+	$(F90) $(OMP) cdfsections.f90  -o $(BINDIR)/cdfsections eos.o modcdfnames.o $(FFLAGS)
 
 ## Modules
 
-cdfio.o: cdfio.f90 modcdfnames.o
-	$(F90) -c  cdfio.f90 $(FFLAGS)
+cdfio.o: cdfio.F90 modcdfnames.o
+	$(F90) -c  cdfio.F90 $(FFLAGS)
 
 eos.o: eos.f90
-	$(F90) -c eos.f90 $(FFLAGS)
+	$(F90) $(OMP) -c eos.f90 $(FFLAGS)
 
 cdftools.o: cdfio.o cdftools.f90
 	$(F90) -c cdftools.f90 $(FFLAGS)
@@ -457,23 +552,37 @@ clean:
 cleanexe: clean
 	( cd $(BINDIR) ; \rm -f $(EXEC) )
 
-man: cdftools.1
+man: cdftools.1 cdftools.html
 
 cdftools.1: cdftools.opod
 	pod2man --center "CDFTOOLS / NEMO Documentation" \
 	  --release "SVN Revision $$(LANG=C svn update | grep '^At rev' | awk '{print $$3}' | cut -f 1 -d '.')" \
 	  cdftools.opod > cdftools.1
 
+cdftools.html: cdftools.opod
+	pod2html --infile=cdftools.opod --outfile=cdftools.html --title="CDFTOOLS Man pages" --css="./cdftools.css"
+
 cdftools.opod: $(EXEC) cdftools-begin.pod cdftools-end.pod
 	cat cdftools-begin.pod > cdftools.opod
-	for s in $$( cd $(BINDIR); ls -1 ); do echo ''; echo "=head2 $$s"; echo ''; $$s; done >> cdftools.opod
+	for s in $$( cd $(BINDIR); ls -1 ); do echo ''; echo "=head2 $$s"; echo ''; $(BINDIR)/$$s; done >> cdftools.opod
+	echo ' ' >> cdftools.opod
+	echo "=head1 AUTHORS" >> cdftools.opod
+	echo ' ' >> cdftools.opod
+	echo "Project headed  by Jean-Marc Molines, (IGE, Grenoble - France)" >> cdftools.opod
+	echo ' ' >> cdftools.opod
+	grep -A1000  -i contribu ../License/CDFTOOLSCeCILL.txt | grep -m1 -B1000 ^$$ >> cdftools.opod
+	echo ' ' >> cdftools.opod
 	cat cdftools-end.pod >> cdftools.opod
 
 install:
 	@mkdir -p $(INSTALL)
-	cd bin ; \cp $(EXEC)  $(INSTALL)
+	cd ../bin ; \cp $(EXEC)  $(INSTALL)
 
 installman:
 	@mkdir -p $(INSTALL_MAN)/man1;
 	\cp -f cdftools.1 $(INSTALL_MAN)/man1/;
 	for s in $$( cd $(BINDIR); ls -1 ); do ( cd $(INSTALL_MAN)/man1/; ln -sf cdftools.1 $$s.1 ); done;
+	\cp -f cdftools.html ../DOC/
+f2py:
+	f2py -c --fcompiler=gnu95 -m cdftoolspython cdficediags.f90 cdfio.o modcdfnames.o  -I$(EBROOTNETCDFMINFORTRAN)/include -L$(EBROOTNETCDFMINFORTRAN)/lib64 -lnetcdf -lnetcdff
+
diff --git a/cdf16bit.f90 b/src/cdf16bit.f90
similarity index 100%
rename from cdf16bit.f90
rename to src/cdf16bit.f90
diff --git a/cdf2levitusgrid2d.f90 b/src/cdf2levitusgrid2d.f90
similarity index 100%
copy from cdf2levitusgrid2d.f90
copy to src/cdf2levitusgrid2d.f90
diff --git a/cdf2levitusgrid2d.f90 b/src/cdf2levitusgrid3d.f90
similarity index 87%
rename from cdf2levitusgrid2d.f90
rename to src/cdf2levitusgrid3d.f90
index dfbd269..122b284 100644
--- a/cdf2levitusgrid2d.f90
+++ b/src/cdf2levitusgrid3d.f90
@@ -1,6 +1,6 @@
-PROGRAM cdf2levitusgrid2d
+PROGRAM cdf2levitusgrid3d
    !!======================================================================
-   !!                     ***  PROGRAM  cdf2levitusgrid2d  ***
+   !!                     ***  PROGRAM  cdf2levitusgrid3d  ***
    !!=====================================================================
    !!  ** Purpose : remaps (bin) 2D high resolution (finer than 1x1 deg)
    !!               fields on Levitus 2D 1x1 deg grid
@@ -17,7 +17,7 @@ PROGRAM cdf2levitusgrid2d
    USE modutils
    !!----------------------------------------------------------------------
    !! CDFTOOLS_3.0 , MEOM 2012
-   !! $Id$
+   !! $Id: cdf2levitusgrid3d.f90 652 2013-04-17 16:27:00Z molines $
    !! Copyright (c) 2012, J.-M. Molines
    !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
    !!----------------------------------------------------------------------
@@ -25,9 +25,10 @@ PROGRAM cdf2levitusgrid2d
 
    INTEGER(KIND=4)                              :: ji, jj, jk, jt     ! dummy loop index
    INTEGER(KIND=4)                              :: jilev,jjlev        ! dummy loop index
-   INTEGER(KIND=4)                              :: jvar, numvar0      ! dummy loop index
+   INTEGER(KIND=4)                              :: jvar               ! dummy loop index
    INTEGER(KIND=4)                              :: ii, ij             ! array index (not loop)
    INTEGER(KIND=4)                              :: iilev, ijlev       ! array index (not loop)
+   INTEGER(KIND=4)                              :: icount             ! array index (not loop)
    INTEGER(KIND=4)                              :: npiglo, npjglo     ! size of the domain
    INTEGER(KIND=4)                              :: npk, npt           ! size of the domain
    INTEGER(KIND=4)                              :: npilev, npjlev     ! size of the Levitus domain
@@ -35,7 +36,6 @@ PROGRAM cdf2levitusgrid2d
    INTEGER(KIND=4)                              :: ncout              ! ncid of output file
    INTEGER(KIND=4)                              :: ierr               ! error status
    INTEGER(KIND=4)                              :: nvars              ! number of variables in the input file
-   INTEGER(KIND=4)                              :: nvarsout           ! number of variables in the output file
    INTEGER(KIND=4)                              :: iimin, iimax       ! IJ coordinates of the closest points
    INTEGER(KIND=4)                              :: ijmin, ijmax       ! "      "            "
    INTEGER(KIND=4)                              :: imethod=1          ! interpolation method
@@ -46,6 +46,8 @@ PROGRAM cdf2levitusgrid2d
    REAL(KIND=4)                                 :: zradius=120.       ! Distance (km) for the search bubble (FHZ)
    REAL(KIND=4)                                 :: rlon1, rlon2, rlat1, rlat2, rpos
    REAL(KIND=4)                                 :: gphitmin
+   REAL(KIND=4)                                 :: rlev_resol=0.33333333     ! degree
+   REAL(KIND=4)                                 :: rlon0=-180         ! degree
    REAL(KIND=4), DIMENSION(:,:),    ALLOCATABLE :: e1t, e2t           ! horizontal T metrics
    REAL(KIND=4), DIMENSION(:,:),    ALLOCATABLE :: z_in               ! input field
    REAL(KIND=4), DIMENSION(:,:),    ALLOCATABLE :: z_fill             ! output 
@@ -59,6 +61,7 @@ PROGRAM cdf2levitusgrid2d
 
    REAL(KIND=8), DIMENSION(:,:),    ALLOCATABLE :: d_out, d_n         ! output field and weighting field
 
+   CHARACTER(LEN=256)                           :: cdum               ! dummy char variable
    CHARACTER(LEN=256)                           :: cf_in              ! input file name
    CHARACTER(LEN=256)                           :: cf_out             ! output file name ( output)
    CHARACTER(LEN=256)                           :: cf_levitus_mask='levitus_mask.nc'   ! Levitus mask filename
@@ -79,46 +82,63 @@ PROGRAM cdf2levitusgrid2d
 
    LOGICAL                                      :: lchk               ! missing files flag
    LOGICAL                                      :: ltest
+   LOGICAL                                      :: l360=.FALSE.       ! flag for 0-360 layout
    !!----------------------------------------------------------------------
    CALL ReadCdfNames()
 
    narg = iargc()
-   IF ( narg < 3 ) THEN
-      PRINT *,' usage : cdf2levitusgrid2d IN-file OUT-file  VAR-name2D'
+   IF ( narg == 0 ) THEN
+      PRINT *,' usage : cdf2levitusgrid3d -f IN-file -o OUT-file  -v VAR-name3D [-360]'
+      PRINT *,'        [-r resolution] '
       PRINT *,'      '
       PRINT *,'     PURPOSE :'
-      PRINT *,'       remaps (bin) 2D high resolution (finer than 1x1 deg) '
-      PRINT *,'       fields on Levitus 2D 1x1 deg grid                    '
+      PRINT *,'       remaps (bin) 3D high resolution (finer than 1x1 deg) '
+      PRINT *,'       fields on a regular grid. (vertical grid as input grid)  '
       PRINT *,'       (does not work for vector fields)  '
-      PRINT *,'       It assumes that Levitus grid SW grid cell center '
-      PRINT *,'       is (0.5W,89.5S) '
+      PRINT *,'       Resolution can be given as argument, default is ', rlev_resol,' deg.'
       PRINT *,'      '
       PRINT *,'     ARGUMENTS :'
-      PRINT *,'       IN-file  : netcdf input file ' 
-      PRINT *,'       OUT-file : netcdf output file ' 
-      PRINT *,'       VAR-name2D : input variable name for interpolation '
+      PRINT *,'       -f IN-file  : netcdf input file ' 
+      PRINT *,'       -o OUT-file : netcdf output file ' 
+      PRINT *,'       -v VAR-name2D : input variable name for interpolation '
       PRINT *,'      '
       PRINT *,'     OPTIONS :'
-      PRINT *,'      '
+      PRINT *,'       -360 : outfile is defined from 0 to 360 deg'
+      PRINT *,'              Default is from -180 to 180 '
+      PRINT *,'       -r  : resolution.'
+      PRINT *,'     '
       PRINT *,'     REQUIRED FILES :'
       PRINT *,'       ',TRIM(cn_fhgr)
       PRINT *,'       ',TRIM(cn_fmsk)
-      PRINT *,'       ',TRIM(cf_levitus_mask)
       PRINT *,'      '
       PRINT *,'     OUTPUT : '
       PRINT *,'       netcdf file : name given as second argument'
-      PRINT *,'         variables : 2d_var_name'
+      PRINT *,'         variables : 3d_var_name'
       STOP
    ENDIF
 
    ijarg = 1
-   CALL getarg(ijarg, cf_in)  ; ijarg = ijarg + 1
-   CALL getarg(ijarg, cf_out) ; ijarg = ijarg + 1
-   CALL getarg(ijarg, cv_nam) ; ijarg = ijarg + 1
+   DO WHILE ( ijarg <= narg ) 
+     CALL getarg( ijarg, cdum)  ; ijarg = ijarg + 1
+     SELECT CASE (cdum)
+     CASE ( '-f' )
+       CALL getarg(ijarg, cf_in)  ; ijarg = ijarg + 1
+     CASE ( '-o' )
+       CALL getarg(ijarg, cf_out) ; ijarg = ijarg + 1
+     CASE ( '-v' )
+       CALL getarg(ijarg, cv_nam) ; ijarg = ijarg + 1
+     CASE ( '-360' )
+       l360=.TRUE.
+       rlon0 = 0.
+     CASE ( '-r' )
+       CALL getarg( ijarg, cdum)  ; ijarg = ijarg + 1
+       READ(cdum,*) rlev_resol
+     END SELECT
+   ENDDO
+
 
    lchk = chkfile (cn_fhgr)
    lchk = chkfile (cn_fmsk)         .OR. lchk
-   lchk = chkfile (cf_levitus_mask) .OR. lchk
    lchk = chkfile (cf_in)           .OR. lchk
    IF ( lchk ) STOP ! missing files
 
@@ -126,14 +146,15 @@ PROGRAM cdf2levitusgrid2d
    npjglo = getdim(cf_in,cn_y)
    npk    = getdim(cf_in,cn_z)
    npt    = getdim(cf_in,cn_t)
-   npilev = getdim(cf_levitus_mask,cn_x)
-   npjlev = getdim(cf_levitus_mask,cn_y)
+
+   npilev = NINT(360./rlev_resol)
+   npjlev = NINT(180./rlev_resol)
 
    nvars = getnvar(cf_in)
    ALLOCATE (cv_names(nvars) )
    ALLOCATE (stypvar(nvars)  , stypvarout(1))
    ALLOCATE (id_var(nvars), ipk(nvars), id_varout(1), ipkout(1))
-   ALLOCATE ( zbt(npiglo,npjglo) , z_in(npiglo,npjglo) )
+   ALLOCATE (zbt(npiglo,npjglo) , z_in(npiglo,npjglo) )
 
    ! get list of variable names and collect attributes in stypvar (optional)
    cv_names(:) = getvarname(cf_in, nvars, stypvar)
@@ -151,17 +172,13 @@ PROGRAM cdf2levitusgrid2d
       IF ( TRIM(cv_names(jk)) == TRIM(cv_nam) ) THEN
          ipkout(ii) = ipk(jk)
          stypvarout(ii) = stypvar(jk)
-         stypvarout(ii)%rmissing_value=getspval ( cf_in, TRIM(cv_nam) )
-         PRINT*, 'rmissing_value = ', stypvarout(ii)%rmissing_value
-         nvarsout = ii
-         numvar0 = jk
       ENDIF
    ENDDO
-   z_in(:,:) = getvar(cf_in, cv_names(numvar0), 1, npiglo, npjglo)
 
    ! Allocate the memory
    ALLOCATE ( e1t(npiglo,npjglo), e2t(npiglo,npjglo) )
    ALLOCATE ( glamt(npiglo,npjglo), gphit(npiglo,npjglo)  )
+
    ALLOCATE ( d_out(npilev,npjlev) , d_n(npilev,npjlev) )
    ALLOCATE ( tmask(npiglo,npjglo) , tmasklev(npilev,npjlev))
    ALLOCATE ( rlonlev(npilev,npjlev), rlatlev(npilev,npjlev) )
@@ -175,22 +192,31 @@ PROGRAM cdf2levitusgrid2d
    glamt = getvar(cn_fhgr, cn_glamt, 1, npiglo, npjglo)
    gphit = getvar(cn_fhgr, cn_gphit, 1, npiglo, npjglo)
    gphitmin = MINVAL(gphit(:,1))
-   WHERE ( glamt < 0. )
-      glamt = glamt + 360. 
-   END WHERE
-
-   ! get the tmask from the byte_mask file
-   tmask(:,:) = getvar(cn_fmsk, 'tmask', 1, npiglo, npjglo)
+   IF ( l360 ) THEN
+     WHERE ( glamt < 0. )
+       glamt = glamt + 360. 
+     END WHERE
+   ENDIF
 
    ! get the longitude,latitude,mask from the input Levitus mask file
-   rlonlev(:,:)  = getvar(cf_levitus_mask, 'nav_lon',  1, npilev, npjlev)
-   rlatlev(:,:)  = getvar(cf_levitus_mask, 'nav_lat' , 1, npilev, npjlev)
-   tmasklev(:,:) = getvar(cf_levitus_mask, 'mask',     1, npilev, npjlev)
+   rlonlev(:,1) = (/ (rlon0+rlev_resol*ji , ji=1,npilev ) /)
+   DO jj=2, npjlev
+      rlonlev(:,jj) = rlonlev(:,1)
+   ENDDO
+   rlatlev(1,:) = (/ (rlev_resol*jj - 90.  , jj=1,npjlev ) /)
+   DO ji=2, npilev
+      rlatlev(ji,:) = rlatlev(1,:)
+   ENDDO
+!  rlonlev(:,:)  = getvar(cf_levitus_mask, 'nav_lon',  1, npilev, npjlev)
+!  rlatlev(:,:)  = getvar(cf_levitus_mask, 'nav_lat' , 1, npilev, npjlev)
+!  tmasklev(:,:) = getvar(cf_levitus_mask, 'mask',     1, npilev, npjlev)
+   tmasklev(:,:) = 1.
+
 
    ! create output fileset
-   ncout = create      (cf_out, cf_levitus_mask, npilev, npjlev, 0 ,cdlonvar='lon', cdlatvar='lat'  )
+   ncout = create      (cf_out,  cf_in, npilev, npjlev, npk ,cdlonvar='lon', cdlatvar='lat'  )
    ierr  = createvar   (ncout ,  stypvarout, 1,      ipkout,    id_varout    )
-   ierr  = putheadervar(ncout ,  'dummy', npilev, npjlev, 0 , pnavlon=rlonlev, pnavlat=rlatlev )
+   ierr  = putheadervar(ncout ,  cf_in, npilev, npjlev, npk , pnavlon=rlonlev, pnavlat=rlatlev )
 
    tim  = getvar1d(cf_in, cn_vtimec, npt     )
    ierr = putvar1d(ncout, tim,       npt, 'T')
@@ -202,7 +228,11 @@ PROGRAM cdf2levitusgrid2d
    zbt(:,:) = e1t(:,:) * e2t(:,:)    ! for surface weighting
 
    DO jt = 1, npt
-      PRINT *,'jt = ', jt
+      DO jk = 1, npk
+      PRINT *,'jt = ', jt,' jk = ', jk
+      ! get the tmask from the byte_mask file
+      tmask(:,:) = getvar(cn_fmsk, 'tmask', jk, npiglo, npjglo)
+      z_in (:,:) = getvar(cf_in, cv_nam, jk, npiglo, npjglo, ktime=jt)
       ! Compute spatial mean by bin
       !-----------------------------
       ! Perform bining of the input file on the Levitus grid.
@@ -211,8 +241,8 @@ PROGRAM cdf2levitusgrid2d
       d_n  (:,:) = 0.d0
       DO jj=1,npjglo
          DO ji=1,npiglo
-            iilev = MIN( 360, INT( glamt(ji,jj) ) + 1)
-            ijlev = MIN (180 , INT( gphit(ji,jj) + 90. ) + 1)
+            iilev = MIN( npilev,  INT( (glamt(ji,jj)-rlon0)/rlev_resol ) + 1)
+            ijlev = MIN (npjlev , INT( (gphit(ji,jj)+ 90.)/rlev_resol ) + 1)
             !IF ( iilev < 1 .OR. iilev .GT. 360 ) print*, 'iilev, glamt = ',iilev,glamt(ji,jj)
             !IF ( ijlev < 1 .OR. ijlev .GT. 180 ) print*, 'ijlev, gphit = ',ijlev,gphit(ji,jj)
             IF ( z_in(ji,jj) /=  stypvarout(1)%rmissing_value ) THEN
@@ -229,12 +259,15 @@ PROGRAM cdf2levitusgrid2d
       END WHERE
 
       ! Check if there are points with missing values on Levitus grid
-      IF ( COUNT( d_out == stypvarout(1)%rmissing_value .AND. tmasklev == 1. ) /=  0. ) THEN
+      icount= COUNT( d_out == stypvarout(1)%rmissing_value .AND. tmasklev == 1. )
+      IF ( icount /=  0. ) THEN
          ALLOCATE ( z_fill(npilev,npjlev) )
          z_fill(:,:) = 0.
          !
-         imethod = 1
+         imethod = 0
          SELECT CASE (imethod)
+         CASE ( 0 ) 
+              PRINT *, 'no filling, even if required for ',icount
          CASE ( 1 ) ! Method 1: fill missing data with shapiro
             ctyp='fill'
             iter_shap = 3  ! number of shapiro iteration
@@ -439,7 +472,8 @@ PROGRAM cdf2levitusgrid2d
       ENDIF !  filling points
       ! ----------------------------------------------------------------------------------------
       ! write 
-      ierr = putvar(ncout, id_varout(1), REAL(d_out(:,:)), 1, npilev, npjlev, ktime=jt)
+      ierr = putvar(ncout, id_varout(1), REAL(d_out(:,:)), jk, npilev, npjlev, ktime=jt)
+     ENDDO ! jk
 
    END DO ! loop on time
 
@@ -521,4 +555,4 @@ CONTAINS
 
    END SUBROUTINE btoe
 
-END PROGRAM cdf2levitusgrid2d
+END PROGRAM cdf2levitusgrid3d
diff --git a/cdf2matlab.f90 b/src/cdf2matlab.f90
similarity index 100%
rename from cdf2matlab.f90
rename to src/cdf2matlab.f90
diff --git a/src/cdf_xtrac_brokenline.f90 b/src/cdf_xtrac_brokenline.f90
new file mode 100644
index 0000000..9a90820
--- /dev/null
+++ b/src/cdf_xtrac_brokenline.f90
@@ -0,0 +1,1030 @@
+PROGRAM cdf_xtract_brokenline
+   !!======================================================================
+   !!                     ***  PROGRAM  cdf_xtract_brokenline  ***
+   !!=====================================================================
+   !!  ** Purpose : Extract temperature, Salinity and velocity components
+   !!               along a broken line formed by various legs
+   !!
+   !!  ** Method  : A broken line is defined by various segments or leg.
+   !!               Each leg is defined by its starting and endig point
+   !!               given as geographical coordinates on standard input.
+   !!
+   !!
+   !! History : 2.1  : 12/2009  : R. Dussin    : Original code
+   !!           3.0  : 01/2011  : J.M. Molines : Doctor norm + Lic.
+   !!           3.0  : 05/2013  : T. Penduff & R. Dussin  : Saving new variables
+   !!           3.0  : 05/2013  : J.M. Molines : Code review, generalization 
+   !!           3.0  : 06/2013  : J.M. Molines : allows multiple section files (optimization).
+   !!----------------------------------------------------------------------
+   !!----------------------------------------------------------------------
+   !!   routines      : description
+   !!----------------------------------------------------------------------
+   USE cdfio
+   USE cdftools
+   USE modcdfnames
+   !!----------------------------------------------------------------------
+   !! CDFTOOLS_3.0 , MEOM 2011
+   !! $Id$
+   !! Copyright (c) 2011, J.-M. Molines
+   !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+   !!----------------------------------------------------------------------
+   IMPLICIT NONE
+
+   INTEGER(KIND=4) :: jsec, jleg, jt, jk,  jipt, jvar ! dummy loop index
+   INTEGER(KIND=4) :: narg, iargc, ijarg, ifree       ! command line
+   INTEGER(KIND=4) :: numin=10                        ! logical unit for input section file
+   INTEGER(KIND=4) :: numout=11                       ! logical unit for output section.dat (used in cdftransport)
+   INTEGER(KIND=4) :: npiglo, npjglo, npk, npt        ! size of the domain
+   INTEGER(KIND=4) :: iimin, iimax, ijmin, ijmax      ! ending points of a leg in model I J
+   INTEGER(KIND=4) :: ii, ij, ii1, ij1, ipoint        ! working integer
+   INTEGER(KIND=4) :: ierr                            ! Netcdf error and ncid
+   INTEGER(KIND=4) :: nvar = 16                       ! number of output variables (modified after if options)
+   INTEGER(KIND=4) :: np_tem, np_sal, np_una, np_vna  ! index for output variable
+   INTEGER(KIND=4) :: np_isec, np_jsec, np_e2vn       !  "
+   INTEGER(KIND=4) :: np_e1vn, np_e3un, np_e3vn       !  "
+   INTEGER(KIND=4) :: np_vmod, np_e1v,  np_e3v        !  "
+   INTEGER(KIND=4) :: np_vmsk, np_baro, np_bat        !  "
+   INTEGER(KIND=4) :: np_ssh,  np_mld,  np_vt, np_vs  !  "
+   INTEGER(KIND=4) :: np_icethick, np_icefra          !  "
+   INTEGER(KIND=4), DIMENSION(:), ALLOCATABLE :: ncout                     ! Netcdf error and ncid
+   INTEGER(KIND=4), DIMENSION(:), ALLOCATABLE :: ipk, id_varout  ! netcdf output stuff
+
+   ! broken line definition
+   INTEGER(KIND=4) :: nsec = 1                       ! number of sections
+   INTEGER(KIND=4) :: nn                             ! working integer (number of points in a leg)
+   INTEGER(KIND=4) :: nstamax                        ! maximum number of points per defined broken line
+   INTEGER(KIND=4) :: npsecmax                       ! maximum number of points per defined model broken line
+   INTEGER(KIND=4) :: ista                           ! working integer
+   INTEGER(KIND=4), DIMENSION(:),     ALLOCATABLE :: npsec            ! number of points defining the model broken line
+   INTEGER(KIND=4), DIMENSION(:),     ALLOCATABLE :: nsta             ! number of points defining the broken line
+   INTEGER(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: normu_sec, normv_sec ! velocity normalization per section
+   INTEGER(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: iisec, ijsec     ! F-index of points on the broken line
+   INTEGER(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: norm_u, norm_v   ! velocity normalization per leg
+   INTEGER(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: iista, ijsta     ! I,J position of the point on the broken line
+   INTEGER(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: ikeepn           ! Number of points per leg
+   INTEGER(KIND=4), DIMENSION(:,:,:), ALLOCATABLE :: iilegs, ijlegs   ! F-index of points on the broken line per leg
+
+   REAL(KIND=4)                              :: xmin, xmax, ymin, ymax !
+   REAL(KIND=4)                              :: ztmp
+
+   REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim                 ! Model time array
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: rxx, ryy            ! leg i j index of F points
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: rlonsta, rlatsta    ! Geographic position defining legs
+
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e1v, e3v            ! V point relevant metric
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e2u, e3u            ! U point relevant metric
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: hdepw               ! model bathymetry
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: rmbat               ! model bathymetry (levels)
+
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: rlonu, rlatu        ! model long and lat of U points
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: rlonv, rlatv        ! model long and lat of U points
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: rlonf, rlatf        ! model long and lat of F points
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: temper, saline      ! model Temperature and salinity
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: uzonal, vmerid      ! model zonal and meridional velocity
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: ssh, rmld           ! model SSH and MLD
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: ricethick, ricefra  ! ice thickness and fraction
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zvmod               ! ice thickness and fraction
+   ! along section array (dimension x,z or x,1 )
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: tempersec, salinesec, uzonalsec, vmeridsec
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: sshsec, rmldsec
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: ricethicksec, ricefrasec
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: rlonsec, rlatsec, risec, rjsec
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: e3usec, e3vsec
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: batsec
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: vmasksec
+   REAL(KIND=4), DIMENSION(:,:,:), ALLOCATABLE :: e1vsec, e2usec  ! 3rd dimension for sections
+
+   REAL(KIND=8)                              :: dtmp    ! temporary cumulating variable
+   REAL(KIND=8), DIMENSION(:), ALLOCATABLE   :: dbarot  ! for barotropic transport computation
+
+   CHARACTER(LEN=255) :: cf_tfil , cf_ufil, cf_vfil   ! input T U V files
+   CHARACTER(LEN=255) :: cf_icefil                    ! input ice file
+   CHARACTER(LEN=255) :: cf_root=''                   ! root name used as prefix
+   CHARACTER(LEN=255) :: cf_out                       ! output file
+   CHARACTER(LEN=255) :: cf_secdat                    ! output section file (suitable for cdftransport or cdfsigtrp)
+   CHARACTER(LEN=255) :: cverb='n'                    ! verbose key for findij
+   CHARACTER(LEN=5  ) :: cstar, cend                  ! dummy character variable
+   CHARACTER(LEN=255) :: cldum                        ! can handle a long list of section files ...
+   CHARACTER(LEN=255), DIMENSION(:), ALLOCATABLE :: cf_sec    ! input section file dim: nsec
+   CHARACTER(LEN=255), DIMENSION(:), ALLOCATABLE :: csection  ! section name
+
+   LOGICAL  :: lchk                                  ! flag for missing files
+   LOGICAL  :: lverbose = .FALSE.                    ! flag for verbosity
+   LOGICAL  :: lsecfile = .FALSE.                    ! flag for input section file
+   LOGICAL  :: lssh     = .FALSE.                    ! flag for saving ssh
+   LOGICAL  :: lmld     = .FALSE.                    ! flag for saving mld
+   LOGICAL  :: lice     = .FALSE.                    ! flag for saving ice*
+   LOGICAL  :: lvt      = .FALSE.                    ! flag for saving products vt, vs
+   LOGICAL  :: ll_ssh, ll_mld, ll_ice                ! working flag for jk =1
+
+   TYPE (variable), DIMENSION(:), ALLOCATABLE :: stypvar  ! variable definition and attributes
+   !!----------------------------------------------------------------------
+   ! 1. : Initialization
+   ! --------------------
+   CALL ReadCdfNames()
+
+   ! check argument number and show usage if necessary
+   narg = iargc()
+   IF ( narg < 3 ) THEN
+      PRINT *,' usage :  cdf_xtrac_brokenline T-file U-file V-file [ice-file] ....'
+      PRINT *,'    [-f section_filei,sec_file2, ... ] [-verbose] [-ssh ] [-mld] [-ice] '
+      PRINT *,'    [-vt] [-o ROOT_name]'
+      PRINT *,'      '
+      PRINT *,'     PURPOSE :'
+      PRINT *,'        This tool extracts model variables from model files for a geographical' 
+      PRINT *,'      broken line, similar to an oceanographic campaign where an oceanic '
+      PRINT *,'      section is formed by one or more legs.' 
+      PRINT *,'        The broken line is specified by the position of ending points of each'
+      PRINT *,'      leg, given in an ASCII file. OVIDE section is taken as default, when no'
+      PRINT *,'      section file is provided.'
+      PRINT *,'        This tool provides a netcdf file similar to a model file, but with a '
+      PRINT *,'      degenerated y dimension (1). In order to be able to use standard CDFTOOLS'
+      PRINT *,'      relevant metric variables are saved into the output file, such as pseudo'
+      PRINT *,'      e1v and e3v_ps and vmask. Therefore the output file can be considered as'
+      PRINT *,'      a mesh_hgr, mesh_zgr and mask file for any ''meridional'' computation.'
+      PRINT *,'        This tools works with temperatures, salinities and normal velocities.'
+      PRINT *,'      The broken line is approximated in the model, by a succession of segments'
+      PRINT *,'      joining F-points. The velocity is taken as either U or V depending on the'
+      PRINT *,'      orientation of the segment, temperatures and salinities are interpolated'
+      PRINT *,'      on the velocity points. When progressing along the broken line, velocity'
+      PRINT *,'      is positive when heading to the right of the progression.' 
+      PRINT *,'        The barotropic transport across the broken line is computed, using the'
+      PRINT *,'      same sign convention. On a closed broken line, the barotropic transport'
+      PRINT *,'      should be very small.'
+      PRINT *,'      ' 
+      PRINT *,'     ARGUMENTS :'
+      PRINT *,'      T-file   :  model gridT file '
+      PRINT *,'      U-file   :  model gridU file '
+      PRINT *,'      V-file   :  model gridV file '
+      PRINT *,'      ice-file :  model ice file '
+      PRINT *,'      ' 
+      PRINT *,'     OPTIONS :'
+      PRINT *,'      -f section_file1,section_file2,... : provide a comma separated list of'
+      PRINT *,'              files for section definition. Section_file is an ascii file as '
+      PRINT *,'              follows:'
+      PRINT *,'             * line #1 : name of the section (e.g. ovide). '
+      PRINT *,'                  Will be used for naming the output file.'
+      PRINT *,'             * line #2 : number of points defining the broken line.'
+      PRINT *,'             * line #3-end : a pair of Longitude latitude values defining'
+      PRINT *,'                   the points. If not supplied, use hard-coded information'
+      PRINT *,'                   for OVIDE section. A comment can be added at the end of'
+      PRINT *,'                   of the lines, using a # as separator'
+      PRINT *,'      -verbose : increase verbosity  ' 
+      PRINT *,'      -ssh     : also save ssh along the broken line.'
+      PRINT *,'      -mld     : also save mld along the broken line.'
+      PRINT *,'      -ice     : also save ice properties along the broken line.'
+      PRINT *,'      -vt      : also save products vt and vs along the broken line.'
+      PRINT *,'      -o ROOT-name : specified the prefix to be used for the output file name.'
+      PRINT *,'                 Note that it may be a good idea to include a separator '
+      PRINT *,'                 character such as _ at the end of the ROOT_name.'
+      PRINT *,'     '
+      PRINT *,'     REQUIRED FILES :'
+      PRINT *,'      ', TRIM(cn_fhgr),' and ',TRIM(cn_fzgr),' in the current directory ' 
+      PRINT *,'      '
+      PRINT *,'     OUTPUT : '
+      PRINT *,'       netcdf file : <section_name>.nc (default). If -o option is used, the'
+      PRINT *,'                     name will be <ROOT-name><section_name>.nc'
+      PRINT *,'         variables : temperature, salinity, normal velocity, pseudo V metrics,'
+      PRINT *,'                    mask, barotropic transport, bathymetry of velocity points.'
+      PRINT *,'                    Additional variables can be set when using options.'
+      PRINT *,'       ASCII file : <section_name>_section.dat usefull for cdftransport, gives'
+      PRINT *,'                  the position in I,J of the geographical input points.'
+      PRINT *,'      '
+      PRINT *,'     SEE ALSO :'
+      PRINT *,'        cdftransport, cdfmoc, cdfmocsig. This tool replaces cdfovide.' 
+      PRINT *,'      '
+      STOP
+   ENDIF
+
+   ! Decode command line
+   ijarg = 1 ; ifree=0
+   DO WHILE ( ijarg <= narg ) 
+      CALL getarg(ijarg, cldum) ; ijarg = ijarg + 1
+      SELECT CASE  ( cldum   )
+      CASE ( '-verbose' ) ; lverbose=.TRUE.  ; cverb='y'
+      CASE ( '-ssh'     ) ; lssh    =.TRUE.  ; nvar = nvar + 1  ! 
+      CASE ( '-mld'     ) ; lmld    =.TRUE.  ; nvar = nvar + 1  !
+      CASE ( '-ice'     ) ; lice    =.TRUE.  ; nvar = nvar + 2  !
+      CASE ( '-vt '     ) ; lvt     =.TRUE.  ; nvar = nvar + 2  !
+      CASE ( '-o '      ) ;  CALL getarg(ijarg, cf_root) ; ijarg = ijarg + 1  !
+      CASE ( '-f' )       ;  CALL getarg(ijarg, cldum) ; ijarg = ijarg + 1 ; lsecfile=.TRUE.
+         CALL ParseFiles(cldum)        ! many section files can be given separated with comma
+      CASE DEFAULT 
+         ifree = ifree + 1
+         SELECT CASE ( ifree )
+         CASE ( 1 ) ;             cf_tfil   = cldum
+         CASE ( 2 ) ;             cf_ufil   = cldum
+         CASE ( 3 ) ;             cf_vfil   = cldum
+         CASE ( 4 ) ; IF ( lice ) cf_icefil = cldum
+         END SELECT
+      END SELECT
+   ENDDO
+
+   ! check file existence
+   lchk = chkfile(cn_fhgr )
+   lchk = chkfile(cn_fzgr ) .OR. lchk
+   lchk = chkfile(cf_tfil ) .OR. lchk
+   lchk = chkfile(cf_ufil ) .OR. lchk
+   lchk = chkfile(cf_vfil ) .OR. lchk
+   IF ( lsecfile ) THEN 
+      DO jsec = 1, nsec
+         lchk = chkfile(cf_sec(jsec) ) .OR. lchk
+      ENDDO
+   ENDIF
+   IF ( lchk     ) STOP ! missing files
+
+   ! nvar and nsec are  now fixed
+   ALLOCATE( stypvar(nvar), ipk(nvar), id_varout(nvar) )
+   ALLOCATE( csection (nsec),nsta(nsec), ncout(nsec), dbarot(nsec)  )
+
+   ! read section file if required
+   IF ( lsecfile ) THEN
+      nstamax = 0
+      DO jsec =1, nsec
+         OPEN(numin, file=cf_sec(jsec) )
+         READ(numin,'(a)') csection(jsec)
+         READ(numin,*    ) nsta(jsec)
+         nstamax  = MAX( nstamax, nsta(jsec))
+         CLOSE (numin)
+      END DO
+      IF ( lverbose ) PRINT *, 'NSTAMAX = ', nstamax
+      ALLOCATE ( iista(nstamax,nsec), ijsta(nstamax,nsec), ikeepn(nstamax -1,nsec )  )
+      ALLOCATE ( npsec(nsec) )
+      ALLOCATE ( rlonsta(nstamax,nsec), rlatsta(nstamax,nsec) )
+
+      DO jsec =1, nsec
+         OPEN(numin, file=cf_sec(jsec) )
+         READ(numin,'(a)') csection(jsec)
+         READ(numin,*    ) ista
+         DO jipt = 1, ista
+            READ(numin, * ) rlonsta(jipt,jsec), rlatsta(jipt,jsec)
+         ENDDO
+         CLOSE (numin)
+      ENDDO
+   ELSE    ! default to OVIDE section
+      nsec = 1
+      nstamax = 1
+      nsta(1) = 5
+      csection(1) = 'ovide'
+      ALLOCATE ( iista(nstamax,nsec), ijsta(nstamax,nsec), ikeepn(nstamax -1,nsec )  )
+      ALLOCATE ( rlonsta(nstamax,nsec), rlatsta(nstamax,nsec) )
+
+      ! D. Desbruyeres : Location of leg points that define the 4 legs of the OVIDE section
+      rlonsta(1,1) = -43.70 ; rlatsta(1,1) = 59.90    ! 
+      rlonsta(2,1) = -30.30 ; rlatsta(2,1) = 58.90    ! 
+      rlonsta(3,1) = -19.40 ; rlatsta(3,1) = 44.90    ! 
+      rlonsta(4,1) = -12.65 ; rlatsta(4,1) = 40.33    ! 
+      rlonsta(5,1) = -08.70 ; rlatsta(5,1) = 40.33    ! 
+   ENDIF
+
+   ! 2. Find the model F-points along the legs of the section
+   ! --------------------------------------------------------
+   npiglo = getdim (cf_tfil, cn_x)
+   npjglo = getdim (cf_tfil, cn_y)
+   npk    = getdim (cf_tfil, cn_z)
+   npt    = getdim (cf_tfil, cn_t)
+
+   IF ( lverbose ) THEN
+      PRINT *, 'NPIGLO = ', npiglo
+      PRINT *, 'NPJGLO = ', npjglo
+      PRINT *, 'NPK    = ', npk
+      PRINT *, 'NPT    = ', npt
+   ENDIF
+
+   ! input  2D fields
+   ALLOCATE(rlonu(npiglo,npjglo), rlatu(npiglo,npjglo))
+   ALLOCATE(rlonv(npiglo,npjglo), rlatv(npiglo,npjglo))
+   ALLOCATE(rlonf(npiglo,npjglo), rlatf(npiglo,npjglo))
+   ALLOCATE(temper(npiglo,npjglo), saline(npiglo,npjglo))
+   ALLOCATE(uzonal(npiglo,npjglo), vmerid(npiglo,npjglo))
+   ALLOCATE(e1v(npiglo,npjglo))
+   ALLOCATE(e2u(npiglo,npjglo))
+   ALLOCATE(e3u(npiglo,npjglo), e3v(npiglo,npjglo))
+   ALLOCATE(hdepw(npiglo,npjglo), rmbat(npiglo, npjglo))
+   IF ( lssh ) ALLOCATE (ssh (npiglo, npjglo))
+   IF ( lmld ) ALLOCATE (rmld(npiglo, npjglo))
+   IF ( lice ) ALLOCATE(ricethick(npiglo,npjglo),ricefra(npiglo,npjglo))
+
+   ! allocate section working arrays
+   ALLOCATE ( iilegs(nstamax-1, npiglo+npjglo, nsec), ijlegs(nstamax-1, npiglo+npjglo, nsec) )
+   ALLOCATE ( norm_u(nstamax-1, nsec) , norm_v(nstamax-1, nsec) )
+   ALLOCATE ( rxx(npiglo+npjglo, nsec), ryy(npiglo+npjglo, nsec) )
+   ALLOCATE ( tim (npt) )
+
+   iilegs = 0  ; ijlegs = 0 ; npsec(:) = 0
+
+   ! Loop on the sections 
+   npsecmax = 0
+   DO jsec  = 1, nsec
+      ! loop on the legs
+      DO jleg = 1, nsta(jsec)-1
+
+         xmin = rlonsta(jleg,  jsec)
+         ymin = rlatsta(jleg,  jsec)
+         xmax = rlonsta(jleg+1,jsec)
+         ymax = rlatsta(jleg+1,jsec)
+
+         ! return ending points of a leg in I J model coordinates
+         PRINT *,TRIM(csection(jsec)),' leg ',jleg
+         CALL cdf_findij ( xmin, xmax, ymin, ymax, iimin, iimax, ijmin, ijmax, &
+              &            cd_coord=cn_fhgr, cd_point='F', cd_verbose=cverb)
+
+         ! save leg information
+         iista(jleg  , jsec) = iimin
+         ijsta(jleg  , jsec) = ijmin
+         iista(jleg+1, jsec) = iimax
+         ijsta(jleg+1, jsec) = ijmax
+
+         ! find the broken line between P1 (iimin,ijmin) and P2 (iimax, ijmax)
+         CALL broken_line( iimin, iimax, ijmin, ijmax, rxx(:,jsec), ryy(:,jsec), nn, npiglo, npjglo,  &
+              &            norm_u(jleg,jsec), norm_v(jleg,jsec) )
+         ikeepn(jleg,jsec) = nn  ! number of points (F) on leg jleg
+         npsec(jsec)       = npsec(jsec) + nn   ! total number of points (F) on the broken line
+
+         IF ( lverbose) PRINT *, 'Leg ', jleg,' : npoints : ', nn
+
+         IF ( jleg == 1 ) THEN
+            ! we want to ensure that the broken line start in the direction that we specify
+            IF ( INT(rxx(1,jsec)) /= iimin .OR.  INT(ryy(1,jsec)) /= ijmin ) THEN 
+              IF ( lverbose ) PRINT *,' First leg is to be reverse'
+                iilegs(jleg,1:nn,jsec)=rxx(nn:1:-1,jsec)
+                ijlegs(jleg,1:nn,jsec)=ryy(nn:1:-1,jsec)
+              ELSE
+                iilegs(jleg,1:nn,jsec)=rxx(1:nn,jsec)
+                ijlegs(jleg,1:nn,jsec)=ryy(1:nn,jsec)
+              ENDIF
+         ELSE  ! check the continuity between legs
+            IF ( iilegs(jleg-1, ikeepn(jleg-1,jsec),jsec) == rxx(1,jsec) .AND. &
+             &   ijlegs(jleg-1, ikeepn(jleg-1,jsec),jsec) == ryy(1,jsec) ) THEN  ! continuity
+               IF ( lverbose ) PRINT *,' Leg ',jleg ,' is continuous ...'
+               iilegs(jleg,1:nn,jsec)=rxx(1:nn,jsec)
+               ijlegs(jleg,1:nn,jsec)=ryy(1:nn,jsec)
+            ELSE                          ! reverse sense
+               IF ( lverbose ) PRINT *,' Leg ',jleg ,' requires inversion ...'
+               iilegs(jleg,1:nn,jsec)=rxx(nn:1:-1,jsec)
+               ijlegs(jleg,1:nn,jsec)=ryy(nn:1:-1,jsec)
+            END IF
+         ENDIF
+
+         IF ( lverbose) THEN
+            PRINT *, '          Leg      iileg        ijleg rxx          ryy '
+            DO jipt = 1, ikeepn(jleg,jsec)  ! ( nn ! ) 
+               PRINT *, jleg, iilegs(jleg,jipt,jsec), ijlegs(jleg,jipt,jsec) ,rxx(jipt,jsec), ryy(jipt,jsec)
+            END DO
+         ENDIF
+      END DO !! loop on the legs
+      npsecmax = MAX(npsecmax, npsec(jsec))  ! maximum number of point in any section
+   END DO !! loop on the sections
+   IF ( lverbose)  PRINT *,' NPSECMAX = ', npsecmax
+   
+   ! Now can allocate the section arrays 
+   ALLOCATE( rlonsec(npsecmax,  1), rlatsec(npsecmax,1) )
+   ALLOCATE( risec  (npsecmax,  1), rjsec  (npsecmax,1) )
+   ALLOCATE( batsec   (npsecmax-1,1  ), vmasksec (npsecmax-1,npk) )
+   ALLOCATE( tempersec(npsecmax-1,npk), salinesec(npsecmax-1,npk) )
+   ALLOCATE( uzonalsec(npsecmax-1,npk), vmeridsec(npsecmax-1,npk) )
+   ALLOCATE( zvmod (npsecmax-1,1) )  ! working array
+   IF ( lssh ) ALLOCATE ( sshsec (npsecmax-1,1) )
+   IF ( lmld ) ALLOCATE ( rmldsec(npsecmax-1,1) )
+   IF ( lice ) ALLOCATE(ricethicksec(npsecmax-1,1),ricefrasec(npsecmax-1,1))
+
+   ! Next arrays are initialized outside the vertical loop and thus require a section index
+   ALLOCATE ( iisec    (npsecmax,nsec),     ijsec(npsecmax,nsec) ) 
+   ALLOCATE ( normu_sec(npsecmax,nsec), normv_sec(npsecmax,nsec) ) 
+   ALLOCATE ( e2usec   (npsecmax-1,1,nsec), e3usec(npsecmax-1,npk) )
+   ALLOCATE ( e1vsec   (npsecmax-1,1,nsec), e3vsec(npsecmax-1,npk) )
+
+   ! 3. : Extraction along the legs
+   ! ------------------------------
+
+   e1vsec = -9999.
+   e2usec = -9999.
+
+   risec(:,:) = 0.
+   rjsec(:,:) = 0.
+
+   rlonu(:,:) = getvar(cn_fhgr, cn_glamu, 1, npiglo, npjglo)
+   rlatu(:,:) = getvar(cn_fhgr, cn_gphiu, 1, npiglo, npjglo)
+   rlonv(:,:) = getvar(cn_fhgr, cn_glamv, 1, npiglo, npjglo)
+   rlatv(:,:) = getvar(cn_fhgr, cn_gphiv, 1, npiglo, npjglo)
+   rlonf(:,:) = getvar(cn_fhgr, cn_glamf, 1, npiglo, npjglo)
+   rlatf(:,:) = getvar(cn_fhgr, cn_gphif, 1, npiglo, npjglo)
+   e1v(:,:)   = getvar(cn_fhgr, cn_ve1v,  1, npiglo, npjglo)
+   e2u(:,:)   = getvar(cn_fhgr, cn_ve2u,  1, npiglo, npjglo)
+   rmbat(:,:) = getvar(cn_fzgr, cn_mbathy,1, npiglo, npjglo)
+   hdepw(:,:) = getvar(cn_fzgr, cn_hdepw, 1, npiglo, npjglo)
+
+   !  Loop on section for metrics and non z-depending variables
+   DO jsec = 1, nsec   ! loop on sections
+      cf_out    = TRIM(cf_root)//TRIM(csection(jsec))//'.nc'
+      cf_secdat = TRIM(cf_root)//TRIM(csection(jsec))//'_section.dat'
+
+      ipoint = 1
+      DO jleg=1, nsta(jsec) -1      ! loop on legs 
+         ipoint = ipoint -1  ! trick to avoid repetition of points in between legs
+         DO jipt=1, ikeepn(jleg,jsec) 
+            ipoint = ipoint + 1
+            iisec    (ipoint,jsec) = iilegs(jleg,jipt,jsec)  ! i-index
+            ijsec    (ipoint,jsec) = ijlegs(jleg,jipt,jsec)  ! j-index
+            normu_sec(ipoint,jsec) = norm_u(jleg,jsec)
+            normv_sec(ipoint,jsec) = norm_v(jleg,jsec)
+         END DO
+      END DO
+      ! adjust npsec to its real value ( 2nd part of the trick)
+      npsec(jsec) = ipoint
+
+      ! now that we know the model grid and bathy do fancy print of the legs.
+      CALL FancyPrint(jsec)
+
+      ! loop on 2d arrays
+      DO jipt = 1,npsec(jsec)
+         ii = iisec(jipt,jsec)
+         ij = ijsec(jipt,jsec)
+
+         risec  (jipt,1) = ii
+         rjsec  (jipt,1) = ij
+      END DO
+
+      DO jipt=1,npsec(jsec)-1
+         ii  = iisec(jipt  ,jsec) ; ij  = ijsec(jipt  ,jsec)
+         ii1 = iisec(jipt+1,jsec) ; ij1 = ijsec(jipt+1,jsec)
+         IF ( ij1 == ij ) THEN ! horizontal segment
+            e2usec(jipt,1,jsec) = 0.
+            IF ( ii1 > ii ) THEN ! eastward
+               e1vsec (jipt,1,jsec) = e1v  (ii+1,ij)
+               rlonsec(jipt,1) = rlonv(ii+1,ij)
+               rlatsec(jipt,1) = rlatv(ii+1,ij)
+               batsec (jipt,1) = MIN( hdepw(ii+1,ij),  hdepw(ii+1,ij+1) )
+            ELSE
+               e1vsec (jipt,1,jsec) = e1v  (ii,ij)
+               rlonsec(jipt,1) = rlonv(ii,ij)
+               rlatsec(jipt,1) = rlatv(ii,ij)
+               batsec (jipt,1) = MIN( hdepw(ii,ij),  hdepw(ii,ij+1) )
+            ENDIF
+
+         ELSEIF ( ii1 == ii ) THEN ! vertical segment
+            e1vsec(jipt,1,jsec) = 0.
+            IF ( ij1 < ij ) THEN ! southward
+               e2usec (jipt,1,jsec) = e2u  (ii,ij)
+               rlonsec(jipt,1) = rlonu(ii,ij)
+               rlatsec(jipt,1) = rlatu(ii,ij)
+               batsec (jipt,1) = MIN( hdepw(ii,ij),  hdepw(ii+1,ij) )
+            ELSE
+               e2usec (jipt,1,jsec) = e2u  (ii,ij+1)
+               rlonsec(jipt,1) = rlonu(ii,ij+1)
+               rlatsec(jipt,1) = rlatu(ii,ij+1)
+               batsec (jipt,1) = MIN( hdepw(ii,ij+1),  hdepw(ii+1,ij+1) )
+            ENDIF
+
+         ELSE
+            PRINT *, 'problem 1 for JIPT = ', jipt
+            PRINT *, '             I(P2)=',ii1, 'J(P1)=', ii
+            PRINT *, '             J(P2)=',ij1, 'J(P1)=', ij
+            EXIT 
+         ENDIF
+      END DO
+
+      ! Prepare output file ( here because rlonsec and rlatsec required )
+      CALL CreateOutputFile (jsec )
+
+      ierr = putvar (ncout(jsec), id_varout(np_isec), risec(:,1),                            1,  npsec(jsec)  , 1 )
+      ierr = putvar (ncout(jsec), id_varout(np_jsec), rjsec(:,1),                            1,  npsec(jsec)  , 1 )
+      ierr = putvar (ncout(jsec), id_varout(np_e2vn), e2usec(:,1,jsec),                      1,  npsec(jsec)-1, 1 )
+      ierr = putvar (ncout(jsec), id_varout(np_e1vn), e1vsec(:,1,jsec),                      1,  npsec(jsec)-1, 1 )
+      ierr = putvar (ncout(jsec), id_varout(np_e1v ), e2usec(:,1,jsec) + e1vsec(:,1,jsec),   1,  npsec(jsec)-1, 1 )
+      ierr = putvar (ncout(jsec), id_varout(np_bat ), batsec(:,1),                           1,  npsec(jsec)-1, 1 )
+
+   END DO  ! section for non depth dependent
+
+   ! Temperature and salinity are interpolated on the respective U or V  point for better flux computation
+   DO jt=1, npt  ! time loop
+      dbarot(:) = 0.d0    ! reset barotropic transport  for all sections
+      IF ( lssh ) ssh (:,:)     = getvar(cf_tfil  , cn_sossheig, 1, npiglo, npjglo, ktime = jt)
+      IF ( lmld ) rmld(:,:)     = getvar(cf_tfil  , cn_somxl010, 1, npiglo, npjglo, ktime = jt)
+      IF ( lice ) ricethick(:,:) = getvar(cf_icefil, cn_iicethic , 1, npiglo, npjglo, ktime = jt)
+      IF ( lice ) ricefra(:,:)   = getvar(cf_icefil, cn_ileadfra , 1, npiglo, npjglo, ktime = jt)
+
+      DO jk=1,npk   ! level loop , read only once the horizontal slab
+         temper(:,:) = getvar(cf_tfil, cn_votemper, jk, npiglo, npjglo, ktime = jt)
+         saline(:,:) = getvar(cf_tfil, cn_vosaline, jk, npiglo, npjglo, ktime = jt)
+         uzonal(:,:) = getvar(cf_ufil, cn_vozocrtx, jk, npiglo, npjglo, ktime = jt)
+         vmerid(:,:) = getvar(cf_vfil, cn_vomecrty, jk, npiglo, npjglo, ktime = jt)
+         e3u(:,:)    = getvar(cn_fzgr, 'e3u_ps',    jk, npiglo, npjglo, ldiom=.TRUE.)
+         e3v(:,:)    = getvar(cn_fzgr, 'e3v_ps',    jk, npiglo, npjglo, ldiom=.TRUE.)
+
+         ll_ssh = ( lssh .AND. jk == 1 )
+         ll_mld = ( lmld .AND. jk == 1 )
+         ll_ice = ( lice .AND. jk == 1 )
+         tempersec(:,:) = 0.
+         salinesec(:,:) = 0.
+         uzonalsec(:,:) = 0.
+         vmeridsec(:,:) = 0.
+
+         DO jsec = 1, nsec  ! section loop at level jk
+            DO jipt=1,npsec(jsec)-1
+               ii  = iisec(jipt  ,jsec) ; ij  = ijsec(jipt  ,jsec)  ! F point  position
+               ii1 = iisec(jipt+1,jsec) ; ij1 = ijsec(jipt+1,jsec)  ! Next F point position
+               IF ( ij1  == ij ) THEN ! horizontal segment
+                  uzonalsec(jipt,jk) = 0.
+                  e3usec   (jipt,jk) = 0.
+                  IF ( ii1 > ii ) THEN ! eastward
+
+                     IF ( MIN( saline(ii+1,ij) , saline(ii+1,ij+1))  == 0. ) THEN
+                        tempersec(jipt,jk) = 0. ; salinesec(jipt,jk) = 0.
+                        IF ( ll_ssh ) sshsec(jipt,jk) = 0.
+                        IF ( ll_mld ) rmldsec(jipt,jk) = 0.
+                        IF ( ll_ice ) ricethicksec(jipt,jk) = 0.
+                        IF ( ll_ice ) ricefrasec(jipt,jk) = 0.
+                     ELSE
+                        tempersec(jipt,jk) = 0.5 * ( temper(ii+1,ij) + temper(ii+1,ij+1) )
+                        salinesec(jipt,jk) = 0.5 * ( saline(ii+1,ij) + saline(ii+1,ij+1) )
+                        IF ( ll_ssh ) sshsec (jipt,jk) = 0.5 * ( ssh (ii+1,ij) + ssh (ii+1,ij+1) )
+                        IF ( ll_mld ) rmldsec(jipt,jk) = 0.5 * ( rmld(ii+1,ij) + rmld(ii+1,ij+1) )
+                        IF ( ll_ice ) ricethicksec(jipt,jk) = 0.5 * ( ricethick(ii+1,ij) + ricethick(ii+1,ij+1) )
+                        IF ( ll_ice ) ricefrasec(jipt,jk)   = 0.5 * ( ricefra(ii+1,ij) + ricefra(ii+1,ij+1) )
+                     ENDIF
+                     vmeridsec(jipt,jk) = vmerid(ii+1,ij) * normv_sec(jipt,jsec)
+                     e3vsec   (jipt,jk) = e3v   (ii+1,ij)
+
+                  ELSE ! westward
+
+                     IF ( MIN( saline(ii,ij) , saline(ii,ij+1) ) == 0. ) THEN
+                        tempersec(jipt,jk) = 0. ; salinesec(jipt,jk) = 0.
+                        IF ( ll_ssh ) sshsec (jipt,jk) = 0.
+                        IF ( ll_mld ) rmldsec(jipt,jk) = 0.
+                        IF ( ll_ice ) ricethicksec(jipt,jk) = 0.
+                        IF ( ll_ice ) ricefrasec(jipt,jk) = 0.
+                     ELSE
+                        tempersec(jipt,jk) = 0.5 * ( temper(ii,ij) + temper(ii,ij+1) )
+                        salinesec(jipt,jk) = 0.5 * ( saline(ii,ij) + saline(ii,ij+1) )
+                        IF ( ll_ssh ) sshsec (jipt,jk) = 0.5 * ( ssh (ii,ij) + ssh (ii,ij+1) )
+                        IF ( ll_mld ) rmldsec(jipt,jk) = 0.5 * ( rmld(ii,ij) + rmld(ii,ij+1) )
+                        IF ( ll_ice ) ricethicksec(jipt,jk) = 0.5 * ( ricethick(ii,ij) + ricethick(ii,ij+1) )
+                        IF ( ll_ice ) ricefrasec(jipt,jk) = 0.5 * ( ricefra(ii,ij) + ricefra(ii,ij+1) )
+                     ENDIF
+                     vmeridsec(jipt,jk) = vmerid(ii,ij) * normv_sec(jipt,jsec)
+                     e3vsec   (jipt,jk) = e3v   (ii,ij)
+
+                  ENDIF
+               ELSEIF ( ii1 == ii ) THEN ! vertical segment
+                  vmeridsec(jipt,jk) = 0.
+                  e3vsec   (jipt,jk) = 0.
+                  IF ( ij1 < ij ) THEN ! southward
+
+                     IF ( MIN( saline(ii,ij) , saline(ii+1,ij) ) == 0. ) THEN
+                        tempersec(jipt,jk) = 0. ; salinesec(jipt,jk) = 0.
+                        IF ( ll_ssh ) sshsec (jipt,jk) = 0.
+                        IF ( ll_mld ) rmldsec(jipt,jk) = 0.
+                        IF ( ll_ice ) ricethicksec(jipt,jk) = 0.
+                        IF ( ll_ice ) ricefrasec(jipt,jk) = 0.
+                     ELSE
+                        tempersec(jipt,jk) = 0.5 * ( temper(ii,ij) + temper(ii+1,ij) )
+                        salinesec(jipt,jk) = 0.5 * ( saline(ii,ij) + saline(ii+1,ij) )
+                        IF ( ll_ssh ) sshsec (jipt,jk) = 0.5 * ( ssh (ii,ij) + ssh (ii+1,ij) )
+                        IF ( ll_mld ) rmldsec(jipt,jk) = 0.5 * ( rmld(ii,ij) + rmld(ii+1,ij) )
+                        IF ( ll_ice ) ricethicksec(jipt,jk) = 0.5 * ( ricethick(ii,ij) + ricethick(ii+1,ij) )
+                        IF ( ll_ice ) ricefrasec(jipt,jk) = 0.5 * ( ricefra(ii,ij) + ricefra(ii+1,ij) )
+                     ENDIF
+                     uzonalsec(jipt,jk) = uzonal(ii,ij) * normu_sec(jipt,jsec)
+                     e3usec   (jipt,jk) = e3u   (ii,ij)
+
+                  ELSE ! northward
+
+                     IF ( MIN( saline(ii,ij+1) , saline(ii+1,ij+1) ) == 0. ) THEN
+                        tempersec(jipt,jk) = 0. ; salinesec(jipt,jk) = 0.
+                        IF ( ll_ssh ) sshsec (jipt,jk) = 0.
+                        IF ( ll_mld ) rmldsec(jipt,jk) = 0.
+                        IF ( ll_ice ) ricethicksec(jipt,jk) = 0.
+                        IF ( ll_ice ) ricefrasec(jipt,jk) = 0.
+                     ELSE
+                        tempersec(jipt,jk) = 0.5 * ( temper(ii,ij+1) + temper(ii+1,ij+1) )
+                        salinesec(jipt,jk) = 0.5 * ( saline(ii,ij+1) + saline(ii+1,ij+1) )
+                        IF ( ll_ssh ) sshsec (jipt,jk) = 0.5 * ( ssh (ii,ij+1) + ssh (ii+1,ij+1) )
+                        IF ( ll_mld ) rmldsec(jipt,jk) = 0.5 * ( rmld(ii,ij+1) + rmld(ii+1,ij+1) )
+                        IF ( ll_ice ) ricethicksec(jipt,jk) = 0.5 * ( ricethick(ii,ij+1) + ricethick(ii+1,ij+1) )
+                        IF ( ll_ice ) ricefrasec(jipt,jk) = 0.5 * ( ricefra(ii,ij+1) + ricefra(ii+1,ij+1) )
+                     ENDIF
+                     uzonalsec(jipt,jk) = uzonal(ii,ij+1) * normu_sec(jipt,jsec)
+                     e3usec   (jipt,jk) = e3u   (ii,ij+1)
+
+                  ENDIF
+
+               ELSE
+                  PRINT *, 'problem 2 for JIPT = ', jipt, 'JK=', jk
+                  PRINT *, '             I(P2)=',ii1, 'J(P1)=', ii
+                  PRINT *, '             J(P2)=',ij1, 'J(P1)=', ij
+                  EXIT 
+               ENDIF
+
+               ! cumulate transport for barotropic calculation
+               dtmp=1.d0* (uzonalsec(jipt,jk) + vmeridsec(jipt,jk))*    &
+                   &   (e2usec(jipt,1,jsec )+ e1vsec(jipt,1,jsec ))*    &
+                   &   (e3usec(jipt,jk)+ e3vsec(jipt,jk))
+               dbarot(jsec)=dbarot(jsec)+dtmp
+            END DO
+
+            ! output section variable at level jk, in separated output section files
+                        ierr = putvar (ncout(jsec), id_varout(np_tem), tempersec(:,jk), jk, npsec(jsec)-1, 1, ktime=jt )
+                        ierr = putvar (ncout(jsec), id_varout(np_sal), salinesec(:,jk), jk, npsec(jsec)-1, 1, ktime=jt )
+                        ierr = putvar (ncout(jsec), id_varout(np_una), uzonalsec(:,jk), jk, npsec(jsec)-1, 1, ktime=jt )
+                        ierr = putvar (ncout(jsec), id_varout(np_vna), vmeridsec(:,jk), jk, npsec(jsec)-1, 1, ktime=jt )
+            ! along-track normal velocity, horiz. and vert. resolution, and mask
+            zvmod(:,1)= uzonalsec(:,jk) + vmeridsec(:,jk)
+                        ierr = putvar (ncout(jsec), id_varout(np_vmod    ), zvmod(:,1),                jk, npsec(jsec)-1, 1, ktime=jt ) 
+            IF (ll_ssh) ierr = putvar (ncout(jsec), id_varout(np_ssh     ), sshsec (:,jk),              1, npsec(jsec)-1, 1, ktime=jt )
+            IF (ll_mld) ierr = putvar (ncout(jsec), id_varout(np_mld     ), rmldsec(:,jk),              1, npsec(jsec)-1, 1, ktime=jt )
+            IF (ll_ice) ierr = putvar (ncout(jsec), id_varout(np_icethick), ricethicksec(:,jk),         1, npsec(jsec)-1, 1, ktime=jt )
+            IF (ll_ice) ierr = putvar (ncout(jsec), id_varout(np_icefra  ), ricefrasec(:,jk),           1, npsec(jsec)-1, 1, ktime=jt )
+            IF (lvt   ) ierr = putvar (ncout(jsec), id_varout(np_vt      ), zvmod(:,1)*tempersec(:,jk),jk, npsec(jsec)-1, 1, ktime=jt )
+            IF (lvt   ) ierr = putvar (ncout(jsec), id_varout(np_vs      ), zvmod(:,1)*salinesec(:,jk),jk, npsec(jsec)-1, 1, ktime=jt )
+
+            IF ( jt == 1 ) THEN   ! output of time independent variables at first time step only
+               ! save a mask of the section
+               vmasksec(:,:) = 1.
+               WHERE( salinesec(:,:) == 0. ) vmasksec(:,:) = 0.
+
+               ierr = putvar (ncout(jsec), id_varout(np_e3un), e3usec(:,jk),                jk, npsec(jsec)-1, 1 )
+               ierr = putvar (ncout(jsec), id_varout(np_e3vn), e3vsec(:,jk),                jk, npsec(jsec)-1, 1 )
+               ierr = putvar (ncout(jsec), id_varout(np_e3v ), e3usec(:,jk)+e3vsec(:,jk),   jk, npsec(jsec)-1, 1 )
+               ierr = putvar (ncout(jsec), id_varout(np_vmsk), vmasksec(:,jk),              jk, npsec(jsec)-1, 1 )
+            ENDIF
+         END DO  ! section
+      END DO  ! levels
+
+      ! print and output barotropic transport once all levels have been processed
+      DO jsec = 1, nsec
+         PRINT 9010, TRIM(csection(jsec)),' BAROTROPIC TRANSPORT at time ',jt,' = ', dbarot(jsec)/1.d6, ' Sv.'
+         ierr  = putvar0d ( ncout(jsec), id_varout(np_baro), REAL(dbarot(jsec)/1.d6), ktime = jt    )
+      ENDDO
+
+   END DO  ! time 
+
+   ! close all output files
+   DO jsec = 1, nsec
+      ierr = closeout(ncout(jsec))
+   ENDDO
+9010 FORMAT ( "Section :",a15,a,i3,a3,f8.3,a4)
+
+CONTAINS 
+   SUBROUTINE CreateOutputFile(ksec)
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE CreateOutputFile  ***
+      !!
+      !! ** Purpose :  Perform output file creation with all the variables 
+      !!
+      !! ** Method  :  Move this part of the code in a subroutine for clarity
+      !!               All variables are global.  
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER(KIND=4), INTENT(in) :: ksec  ! section index
+      INTEGER(KIND=4)             :: ivar  ! variable index
+      !!----------------------------------------------------------------------
+      ivar = 1
+
+      stypvar%scale_factor= 1.
+      stypvar%add_offset= 0.
+      stypvar%savelog10= 0.
+      stypvar%rmissing_value=0.
+      stypvar%conline_operation='N/A'
+
+      ! define new variables for output 
+      np_tem = ivar
+      stypvar(ivar)%cname       = cn_votemper
+      stypvar(ivar)%cunits      = 'deg C'
+      stypvar(ivar)%valid_min   = -2.
+      stypvar(ivar)%valid_max   = 40.
+      stypvar(ivar)%clong_name  = 'Temperature along '//TRIM(csection(ksec))//' section'
+      stypvar(ivar)%cshort_name = cn_votemper
+      stypvar(ivar)%caxis       = 'TZX'
+      ipk(ivar)                 = npk
+      ivar = ivar + 1
+
+      np_sal = ivar
+      stypvar(ivar)%cname       = cn_vosaline
+      stypvar(ivar)%cunits      = 'PSU'
+      stypvar(ivar)%valid_min   = 0.
+      stypvar(ivar)%valid_max   = 50.
+      stypvar(ivar)%clong_name  = 'Salinity along '//TRIM(csection(ksec))//' section'
+      stypvar(ivar)%cshort_name = cn_vosaline
+      stypvar(ivar)%caxis       = 'TZX'
+      ipk(ivar)                 = npk
+      ivar = ivar + 1
+
+      np_una = ivar
+      stypvar(ivar)%cname       = TRIM(cn_vozocrtx)//'_native'
+      stypvar(ivar)%cunits      = 'm.s-1'
+      stypvar(ivar)%valid_min   = -20.
+      stypvar(ivar)%valid_max   = 20.
+      stypvar(ivar)%clong_name  = 'Zonal velocity along '//TRIM(csection(ksec))//' section'
+      stypvar(ivar)%cshort_name = TRIM(cn_vozocrtx)//'_native'
+      stypvar(ivar)%caxis       = 'TZX'
+      ipk(ivar)                 = npk
+      ivar = ivar + 1
+
+      np_vna = ivar
+      stypvar(ivar)%cname       = TRIM(cn_vomecrty)//'_native'
+      stypvar(ivar)%cunits      = 'm.s-1'
+      stypvar(ivar)%valid_min   = -20.
+      stypvar(ivar)%valid_max   = 20.
+      stypvar(ivar)%clong_name  = 'Meridionnal velocity along '//TRIM(csection(ksec))//' section'
+      stypvar(ivar)%cshort_name = TRIM(cn_vomecrty)//'_native'
+      stypvar(ivar)%caxis       = 'TZX'
+      ipk(ivar)                 = npk
+      ivar = ivar + 1
+
+      np_isec = ivar
+      stypvar(ivar)%cname       = 'isec'
+      stypvar(ivar)%valid_min   = 1.
+      stypvar(ivar)%valid_max   = npiglo 
+      stypvar(ivar)%caxis       = 'TX'
+      ipk(ivar)                 = 1
+      ivar = ivar + 1
+
+      np_jsec = ivar
+      stypvar(ivar)%cname       = 'jsec'
+      stypvar(ivar)%valid_min   = 1.
+      stypvar(ivar)%valid_max   = npjglo 
+      stypvar(ivar)%caxis       = 'TX'
+      ipk(ivar)                 = 1
+      ivar = ivar + 1
+
+      np_e2vn = ivar
+      stypvar(ivar)%cname       = TRIM(cn_ve2u)//'_native'
+      stypvar(ivar)%valid_min   = 1.
+      stypvar(ivar)%valid_max   = 200000.
+      stypvar(ivar)%caxis       = 'TX'
+      ipk(ivar)                 = 1
+      ivar = ivar + 1
+
+      np_e1vn = ivar
+      stypvar(ivar)%cname       = TRIM(cn_ve1v)//'_native'
+      stypvar(ivar)%valid_min   = 1.
+      stypvar(ivar)%valid_max   = 200000.
+      stypvar(ivar)%caxis       = 'TX'
+      ipk(ivar)                 = 1
+      ivar = ivar + 1
+
+      np_e3un = ivar
+      stypvar(ivar)%cname       = 'e3u_native'
+      stypvar(ivar)%valid_min   = 1.
+      stypvar(ivar)%valid_max   = 200000.
+      stypvar(ivar)%caxis       = 'TZX'
+      ipk(ivar)                 =  npk
+      ivar = ivar + 1
+
+      np_e3vn = ivar
+      stypvar(ivar)%cname      = 'e3v_native'
+      stypvar(ivar)%valid_min   = 1.
+      stypvar(ivar)%valid_max   = 200000.
+      stypvar(ivar)%caxis      = 'TZX'
+      ipk(ivar)                =  npk
+      ivar = ivar + 1
+
+      np_vmod = ivar
+      stypvar(ivar)%cname       = cn_vomecrty
+      stypvar(ivar)%cunits      = 'm.s-1'
+      stypvar(ivar)%valid_min   = -20.
+      stypvar(ivar)%valid_max   = 20.
+      stypvar(ivar)%clong_name  = 'Normal velocity along '//TRIM(csection(ksec))//' section'
+      stypvar(ivar)%cshort_name = cn_vomecrty
+      stypvar(ivar)%caxis       = 'TZX'
+      ipk(ivar)                 =  npk
+      ivar = ivar + 1
+
+      np_e1v = ivar
+      stypvar(ivar)%cname       = cn_ve1v
+      stypvar(ivar)%cunits      = 'm'
+      stypvar(ivar)%valid_min   = 0.
+      stypvar(ivar)%valid_max   = 1000000.
+      stypvar(ivar)%clong_name  = 'Local horiz. resolution along '//TRIM(csection(ksec))//' section'
+      stypvar(ivar)%cshort_name = cn_ve1v
+      stypvar(ivar)%caxis       = 'TX'
+      ipk(ivar)                 = 1
+      ivar = ivar + 1
+
+      np_e3v = ivar
+      stypvar(ivar)%cname       = 'e3v_ps'
+      stypvar(ivar)%cunits      = 'm'
+      stypvar(ivar)%valid_min   = 0.
+      stypvar(ivar)%valid_max   = 100000000.
+      stypvar(ivar)%clong_name  = 'Local vert. resolution along '//TRIM(csection(ksec))//' section'
+      stypvar(ivar)%cshort_name = 'e3v_ps'
+      stypvar(ivar)%caxis       = 'TZX'
+      ipk(ivar)                 =  npk
+      ivar = ivar + 1
+
+      np_vmsk = ivar
+      stypvar(ivar)%cname       = 'vmask'
+      stypvar(ivar)%cunits      ='1/0'
+      stypvar(ivar)%valid_min   = 0.
+      stypvar(ivar)%valid_max   = 1.
+      stypvar(ivar)%rmissing_value = 9999.
+      stypvar(ivar)%clong_name  ='Mask along '//TRIM(csection(ksec))//' section'
+      stypvar(ivar)%cshort_name = 'vmask'
+      stypvar(ivar)%caxis       = 'TZX'
+      ipk(ivar)                 =  npk
+      ivar = ivar + 1
+
+      np_baro = ivar
+      stypvar(ivar)%cname       = 'barotrop_'//TRIM(csection(ksec))
+      stypvar(ivar)%cunits      ='Sv'
+      stypvar(ivar)%valid_min   = -500.
+      stypvar(ivar)%valid_max   = 500.
+      stypvar(ivar)%rmissing_value = -99999.
+      stypvar(ivar)%clong_name  = 'Barotropic_transport for '//TRIM(csection(ksec))//' section'
+      stypvar(ivar)%cshort_name = 'barotrop_'//TRIM(csection(ksec))
+      stypvar(ivar)%caxis       = 'T'
+      ipk(ivar)                 =  -1
+      ivar = ivar + 1
+
+      np_bat = ivar
+      stypvar(ivar)%cname       = 'Bathymetry'
+      stypvar(ivar)%cunits      = 'm'
+      stypvar(ivar)%valid_min   = 0.
+      stypvar(ivar)%valid_max   = 1000000.
+      stypvar(ivar)%clong_name  = 'Bathymetry along '//TRIM(csection(ksec))//' section'
+      stypvar(ivar)%cshort_name = 'Bathymetry'
+      stypvar(ivar)%caxis       = 'TX'
+      ipk(ivar)                 = 1
+      ivar = ivar + 1
+
+      IF ( lssh ) THEN
+         np_ssh = ivar
+         stypvar(ivar)%cname       = cn_sossheig
+         stypvar(ivar)%cunits      = 'm'
+         stypvar(ivar)%valid_min   = 0.
+         stypvar(ivar)%valid_max   = 1000000.
+         stypvar(ivar)%clong_name  = 'SSH  along '//TRIM(csection(ksec))//' section'
+         stypvar(ivar)%cshort_name = cn_sossheig
+         stypvar(ivar)%caxis       = 'TX'
+         ipk(ivar)                 = 1
+         ivar = ivar + 1
+      ENDIF
+
+      IF ( lmld ) THEN
+         np_mld = ivar
+         stypvar(ivar)%cname       = cn_somxl010
+         stypvar(ivar)%cunits      = 'm'
+         stypvar(ivar)%valid_min   = 0.
+         stypvar(ivar)%valid_max   = 100000.
+         stypvar(ivar)%clong_name  = 'Mixed Layer Depth 0.01  along '//TRIM(csection(ksec))//' section'
+         stypvar(ivar)%cshort_name = cn_somxl010
+         stypvar(ivar)%caxis       = 'TX'
+         ipk(ivar)                 = 1
+         ivar = ivar + 1
+      ENDIF
+
+      IF ( lice ) THEN
+         np_icethick = ivar
+         stypvar(ivar)%cname       = cn_iicethic
+         stypvar(ivar)%cunits      = 'm'
+         stypvar(ivar)%valid_min   = -10000.
+         stypvar(ivar)%valid_max   = 1000000.
+         stypvar(ivar)%clong_name  = 'icethick along '//TRIM(csection(ksec))//' section'
+         stypvar(ivar)%cshort_name = cn_iicethic
+         stypvar(ivar)%caxis       = 'TX'
+         ipk(ivar)                 = 1
+         ivar = ivar + 1
+   
+         np_icefra = ivar
+         stypvar(ivar)%cname       = cn_ileadfra
+         stypvar(ivar)%cunits      = 'm'
+         stypvar(ivar)%valid_min   = -10000.
+         stypvar(ivar)%valid_max   = 1000000.
+         stypvar(ivar)%clong_name  = 'icefra along '//TRIM(csection(ksec))//' section'
+         stypvar(ivar)%cshort_name = cn_ileadfra
+         stypvar(ivar)%caxis       = 'TX'
+         ipk(ivar)                 = 1
+         ivar = ivar + 1
+      ENDIF
+     
+      IF ( lvt ) THEN
+         np_vt = ivar
+         stypvar(ivar)%cname       = cn_vomevt
+         stypvar(ivar)%cunits      = 'C.m/s'
+         stypvar(ivar)%valid_min   = -1000000.
+         stypvar(ivar)%valid_max   = 1000000.
+         stypvar(ivar)%clong_name  = 'VT product along '//TRIM(csection(ksec))//' section'
+         stypvar(ivar)%cshort_name = cn_vomevt
+         stypvar(ivar)%caxis       = 'TZX'
+         ipk(ivar)                 = npk
+         ivar = ivar + 1
+
+         np_vs = ivar
+         stypvar(ivar)%cname       = cn_vomevs
+         stypvar(ivar)%cunits      = 'PSU.m/s'
+         stypvar(ivar)%valid_min   = -1000000.
+         stypvar(ivar)%valid_max   = 1000000.
+         stypvar(ivar)%clong_name  = 'VS product along '//TRIM(csection(ksec))//' section'
+         stypvar(ivar)%cshort_name = cn_vomevs
+         stypvar(ivar)%caxis       = 'TZX'
+         ipk(ivar)                 = npk
+         ivar = ivar + 1
+      ENDIF
+
+      ! create output fileset
+      ncout(ksec) = create      (cf_out, cf_tfil, npsec(ksec),  1, npk, cdep='deptht'                      )
+      ierr  = createvar   (ncout(ksec),  stypvar, nvar,  ipk, id_varout                                    )
+      ierr  = putheadervar(ncout(ksec),  cf_tfil, npsec(ksec)-1,  1, npk, pnavlon=rlonsec, pnavlat=rlatsec )
+      tim   = getvar1d    (cf_tfil, 'time_counter', npt                                                    )
+      ierr  = putvar1d    (ncout(ksec), tim, npt, 'T'                                                      )
+
+   END SUBROUTINE CreateOutputFile
+
+   SUBROUTINE ParseFiles (cdum)
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE ParseFiles  ***
+      !!
+      !! ** Purpose :  Decode -f option from command line 
+      !!
+      !! ** Method  :  look for , in the argument string and set the number of 
+      !!         sections (nsec), allocate cf_sec array and fill it with the 
+      !!         decoded  names.
+      !!
+      !!----------------------------------------------------------------------
+      CHARACTER(LEN=*), INTENT(in) :: cdum
+
+      CHARACTER(LEN=80), DIMENSION(100) :: cl_dum  ! 100 is arbitrary
+      INTEGER  :: ji
+      INTEGER  :: inchar,  i1=1
+      !!----------------------------------------------------------------------
+
+      inchar= LEN(TRIM(cdum))
+      ! scan the input string and look for ',' as separator
+      DO ji=1,inchar
+         IF ( cdum(ji:ji) == ',' ) THEN
+            cl_dum(nsec) = cdum(i1:ji-1)
+            i1=ji+1
+            nsec=nsec+1
+         ENDIF
+      ENDDO
+
+      ! last name of the list does not have a ','
+      cl_dum(nsec) = cdum(i1:inchar)
+
+      ALLOCATE ( cf_sec(nsec) )
+
+      DO ji=1, nsec
+         cf_sec(ji) = cl_dum(ji)
+      ENDDO
+   END SUBROUTINE ParseFiles
+
+   SUBROUTINE FancyPrint(ksec)
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE FancyPrint  ***
+      !!
+      !! ** Purpose :   perform Fancy Print for sections definitions 
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER(KIND=4), INTENT(in) :: ksec
+      !!----------------------------------------------------------------------
+
+      PRINT 9005
+      PRINT 9006, TRIM(csection(ksec))
+      PRINT 9005
+      PRINT 9000
+      PRINT 9005
+
+      OPEN(numout, file=cf_secdat )   ! open section.dat file for output
+
+      DO jleg = 1, nsta(ksec) -1
+         ! start point 
+         ii = iista(jleg,ksec)  ; ij = ijsta(jleg,ksec)
+         ztmp = MIN (rmbat(ii,ij), rmbat(ii+1,ij), rmbat(ii+1,ij+1), rmbat(ii,ij+1) ) 
+         IF ( ztmp == 0. ) THEN 
+            cstar = 'LAND'
+         ELSE
+            cstar = ' SEA'
+         ENDIF
+
+         ! end  point 
+         ii1 = iista(jleg+1,ksec)  ; ij1 = ijsta(jleg+1,ksec)
+         ztmp = MIN (rmbat(ii1,ij1), rmbat(ii1+1,ij1), rmbat(ii1+1,ij1+1), rmbat(ii1,ij1+1) )
+         IF ( ztmp == 0. ) THEN
+            cend = 'LAND'
+         ELSE
+            cend = ' SEA'
+         ENDIF
+         PRINT 9001, jleg, rlatsta(jleg,ksec), rlonsta(jleg,ksec),    rlatsta(jleg+1,ksec), rlonsta(jleg+1,ksec)
+         PRINT 9002,          ii,ij,                        ii1,ij1
+         PRINT 9003, rlatf(ii,ij), rlonf(ii,ij),            rlatf(ii1,ij1), rlonf(ii1,ij1)
+         PRINT 9004, TRIM(cstar),                           TRIM(cend)
+         PRINT 9005
+         WRITE(numout,'(i2.2,"_",a)') jleg, TRIM(csection(ksec))
+         WRITE(numout,*) ii, ii1, ij, ij1
+      ENDDO
+
+      WRITE(numout,'("EOF")')
+      CLOSE(numout)
+
+9000  FORMAT ("  |  Leg #  |    Start point     |      End point     | ")
+9001  FORMAT ("  |   ",i3,"   | ", f6.2," N ", f7.2, " E | ", f6.2," N ", f7.2, " E |" )
+9002  FORMAT ("  |        F| I =", i5,", J =",i5 " | I =", i5,", J =",i5 " |" )
+9003  FORMAT ("  |      mod| ", f6.2," N ", f7.2, " E | ", f6.2," N ", f7.2, " E |" )
+9004  FORMAT ("  |         |      ",a4,"          |     ",a4,"           | ")
+9005  FORMAT ("  |---------|--------------------|--------------------| ")
+9006  FORMAT ("  |    Section : ",a33,"    |" )
+
+   END SUBROUTINE FancyPrint
+
+END PROGRAM cdf_xtract_brokenline
diff --git a/cdfbathy.f90 b/src/cdfbathy.f90
similarity index 87%
rename from cdfbathy.f90
rename to src/cdfbathy.f90
index 25a7325..3d80b2f 100644
--- a/cdfbathy.f90
+++ b/src/cdfbathy.f90
@@ -13,6 +13,7 @@ PROGRAM cdfbathy
   !!
   !! History : 2.1  : 11/2007  : J.M. Molines : Original code
   !!           3.0  : 12/2010  : J.M. Molines : Doctor norm + Lic.
+  !!                : 04/1014  : P. Mathiot   : add fill_pool option
   !!----------------------------------------------------------------------
   !!----------------------------------------------------------------------
   !!   routines      : description
@@ -41,6 +42,7 @@ PROGRAM cdfbathy
   INTEGER(KIND=4)                              :: iimin, iimax        ! selected area
   INTEGER(KIND=4)                              :: ijmin, ijmax        ! selected area
   INTEGER(KIND=4)                              :: ierr                ! error status
+  INTEGER(KIND=4)                              :: icrit               ! maximal size of pool 
   INTEGER(KIND=4)                              :: iklev               ! selected level
   INTEGER(KIND=4)                              :: itime               ! selected time
   INTEGER(KIND=4)                              :: npiglo, npjglo      ! domain size
@@ -76,7 +78,7 @@ PROGRAM cdfbathy
   LOGICAL :: lmodif     = .FALSE., loverwrite = .FALSE.       ! all required flags for options
   LOGICAL :: lraz       = .FALSE., ldumpn     = .FALSE.       ! all required flags for options
   LOGICAL :: lrazb      = .FALSE., lsetb      = .FALSE.       ! all required flags for options
-  LOGICAL :: lchk       = .FALSE.                             ! all required flags for options
+  LOGICAL :: lchk       = .FALSE., lfillpool  = .FALSE.       ! all required flags for options
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
@@ -102,6 +104,7 @@ PROGRAM cdfbathy
      PRINT 9999, '   -scale  s            : use s as a scale factor (divide when read the file)'
      PRINT 9999, '   -zoom (or -z )       : sub area of the bathy file to work with (imin imax jmin jmax)'
      PRINT 9999, '   -fillzone (or -fz )  : sub area will be filled with 0 up to the first coast line '
+     PRINT 9999, '   -fillpool (or -fp ) [ icrit ] : the whole file is check and fill all the pool smaller than (icrit) cell by 0'
      PRINT 9999, '   -raz_zone (or -raz ) : sub area will be filled with 0 up '
      PRINT 9999, '   -raz_below depmin    : any depth less than depmin in subarea will be replaced by 0 '
      PRINT 9999, '      (or -rb depmin )  '
@@ -188,6 +191,10 @@ PROGRAM cdfbathy
      CASE ( '-overwrite' , '-o' ) ! Overwrite modifications in f90 log file
         loverwrite=.TRUE.
      !
+     CASE ( '-fillpool' , '-fp' ) ! Overwrite modifications in f90 log file
+        lfillpool=.TRUE. ; lmodif=.TRUE.
+        CALL getarg(ijarg, cldum) ; ijarg = ijarg +1 ; READ(cldum,*) icrit
+     !
      CASE ( '-replace' , '-r' )   ! Replace zoomed area by values in ascii file
         lreplace=.TRUE. ; lmodif=.TRUE.
         CALL getarg(ijarg, cf_replace) ; ijarg = ijarg +1
@@ -275,6 +282,7 @@ PROGRAM cdfbathy
   IF (ldump     )       CALL dumpzone     (cf_dump, iimin, iimax, ijmin, ijmax)
   IF (ldumpn    )       CALL nicedumpzone (cf_dump, iimin, iimax, ijmin, ijmax)
   IF (lreplace  )       CALL replacezone  (cf_replace)
+  IF (lfillpool )       CALL fillpool  (icrit, iimin, iimax, ijmin, ijmax)
 
   IF (lmodif ) THEN   ! save log 
      CALL prlog(bathyin, bathy, npiglo, npjglo, lappend)
@@ -591,6 +599,89 @@ CONTAINS
     CLOSE(inumrep)
 
   END SUBROUTINE replacezone
+  
+
+  SUBROUTINE fillpool(kcrit, kimin, kimax, kjmin, kjmax) 
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE replacezone  ***
+    !!
+    !! ** Purpose :  Replace all area surrounding by mask value by mask value
+    !!
+    !! ** Method  :  flood fill algorithm
+    !!
+    !!----------------------------------------------------------------------
+    INTEGER, INTENT(in) :: kcrit        ! maximal allowed pool 
+    INTEGER(KIND=4),  INTENT(in) :: kimin, kimax, kjmin, kjmax ! position of the data windows
+
+    INTEGER :: ik                       ! number of point change
+    INTEGER :: ip                       ! size of the pile
+    INTEGER :: ji, jj                   ! loop index
+    INTEGER :: iip1, iim1, ii, ij       ! working integer
+    INTEGER, DIMENSION(:,:), ALLOCATABLE :: ipile    ! pile variable
+    INTEGER, DIMENSION(:,:), ALLOCATABLE :: ioptm    ! matrix to check already tested value 
+
+    REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zbathy   ! new bathymetry
+    !!----------------------------------------------------------------------
+    PRINT *, 'WARNING North fold case not coded'
+    ! allocate variable
+    ALLOCATE(ipile(((kimax-kimin)+1)*((kjmax-kjmin)+1),2))
+    ALLOCATE(zbathy(npiglo,npjglo), ioptm(npiglo,npjglo))
+
+    ioptm = bathy
+    WHERE (ioptm /=  0)
+       ioptm = 1
+    END WHERE
+
+    PRINT *, 'Filling area in progress ... (it can take a while)'    
+
+    DO ji=kimin,kimax
+       IF (mod(ji,100) == 0) PRINT *, ji,'/',npiglo
+       DO jj=kjmin,kjmax
+          ! modify something only if seed point is a non 0 cell
+          IF (ioptm(ji,jj) == 1) THEN
+             ! initialise variables
+             zbathy=bathy
+             ipile(:,:)=0
+             ipile(1,:)=[ji,jj]
+             ip=1; ik=0
+         
+             ! loop until the pile size is 0 or if the pool is larger than the critical size
+             DO WHILE ( ip /= 0 .AND. ik < kcrit);
+                ik=ik+1 
+                ii=ipile(ip,1); ij=ipile(ip,2)
+               
+                ! update bathy and update pile size
+                zbathy(ii,ij)=0.0 
+                ipile(ip,:)  =[0,0]; ip=ip-1
+                
+                ! check neighbour cells and update pile
+                iip1=ii+1; IF ( iip1 == npiglo+1 ) iip1=2
+                iim1=ii-1; IF ( iim1 == 0        ) iim1=npiglo-1
+                IF (zbathy(ii, ij+1) /=  0.0) THEN
+                    ip=ip+1; ipile(ip,:)=[ii  ,ij+1] 
+                    ioptm (ii, ij+1) = 0
+                END IF
+                IF (zbathy(ii, ij-1) /= 0.0) THEN
+                    ip=ip+1; ipile(ip,:)=[ii  ,ij-1]
+                    ioptm(ii, ij-1) = 0
+                END IF
+                IF (zbathy(iip1, ij) /=  0.0) THEN
+                    ip=ip+1; ipile(ip,:)=[iip1,ij  ]
+                    ioptm(iip1, ij) = 0
+                END IF
+                IF (zbathy(iim1, ij) /=  0.0) THEN
+                    ip=ip+1; ipile(ip,:)=[iim1,ij  ]
+                    ioptm(iim1, ij) = 0
+                END IF
+             END DO
+             IF (ik < kcrit) bathy=zbathy;
+          END IF
+       END DO
+    END DO
+ 
+    DEALLOCATE(ipile); DEALLOCATE(zbathy, ioptm)
+
+  END SUBROUTINE
 
 
 END PROGRAM cdfbathy
diff --git a/cdfbci.f90 b/src/cdfbci.f90
similarity index 100%
rename from cdfbci.f90
rename to src/cdfbci.f90
diff --git a/cdfbn2.f90 b/src/cdfbn2.f90
similarity index 100%
rename from cdfbn2.f90
rename to src/cdfbn2.f90
diff --git a/cdfbotpressure.f90 b/src/cdfbotpressure.f90
similarity index 79%
rename from cdfbotpressure.f90
rename to src/cdfbotpressure.f90
index a2943da..6a52b3a 100644
--- a/cdfbotpressure.f90
+++ b/src/cdfbotpressure.f90
@@ -26,8 +26,8 @@ PROGRAM cdfbotpressure
    INTEGER(KIND=4)                           :: narg, iargc, ijarg  ! command line 
    INTEGER(KIND=4)                           :: npiglo, npjglo      ! size of the domain
    INTEGER(KIND=4)                           :: npk, npt            ! size of the domain
-   INTEGER(KIND=4),             DIMENSION(1) :: ipk, id_varout      ! only one output variable
-   INTEGER(KIND=4)                           :: ncout 
+   INTEGER(KIND=4)                           :: ncout, nvar
+   INTEGER(KIND=4),DIMENSION(:), ALLOCATABLE :: ipk, id_varout      ! only one output variable
 
    REAL(KIND=4), PARAMETER                   :: pp_grav = 9.81      ! Gravity
    REAL(KIND=4), PARAMETER                   :: pp_rau0 = 1035.e0   ! Reference density (as in NEMO)
@@ -51,15 +51,16 @@ PROGRAM cdfbotpressure
    LOGICAL                                   :: lfull =.FALSE.      ! flag for full step computation
    LOGICAL                                   :: lssh  =.FALSE.      ! Use ssh and cst surf. density in the bot pressure
    LOGICAL                                   :: lssh2 =.FALSE.      ! Use ssh and variable surf.density in the bot pressure
+   LOGICAL                                   :: lxtra =.FALSE.      ! Save ssh and ssh pressure
    LOGICAL                                   :: lchk  =.FALSE.      ! flag for missing files
 
-   TYPE(variable), DIMENSION(1)              :: stypvar             ! extension for attributes
+   TYPE(variable), DIMENSION(:), ALLOCATABLE :: stypvar             ! extension for attributes
    !!----------------------------------------------------------------------
    CALL ReadCdfNames()
 
    narg= iargc()
    IF ( narg == 0 ) THEN
-      PRINT *,' usage : cdfbotpressure T-file [-full] [-ssh] [-ssh2 ] '
+      PRINT *,' usage : cdfbotpressure T-file [-full] [-ssh] [-ssh2 ] [-xtra ] '
       PRINT *,'      '
       PRINT *,'     PURPOSE :'
       PRINT *,'          Compute the vertical bottom pressure (pa) from in situ density'
@@ -76,6 +77,10 @@ PROGRAM cdfbotpressure
       PRINT *,'                the model, use option -ssh2'
       PRINT *,'        -ssh2 : as option -ssh but surface density is taken from '
       PRINT *,'                the model instead of a constant'
+      PRINT *,'        -xtra :  Using this option, the output file also contains the ssh,'
+      PRINT *,'                and the pressure contribution of ssh to bottom pressure. '
+      PRINT *,'                Require either -ssh or -ssh2 option. Botpressure is still'
+      PRINT *,'                the total pressure, including ssh effect.'
       PRINT *,'      '
       PRINT *,'     REQUIRED FILES :'
       PRINT *,'       ', TRIM(cn_fmsk),' and ', TRIM(cn_fzgr) 
@@ -91,12 +96,13 @@ PROGRAM cdfbotpressure
    ENDIF
 
    ! browse command line
-   ijarg = 1   ; ij = 0
+   ijarg = 1   ; ij = 0 ; nvar = 1
    DO WHILE ( ijarg <= narg ) 
       CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1
       SELECT CASE ( cldum)
       CASE ( '-ssh'  ) ; lssh  = .TRUE. 
       CASE ( '-ssh2' ) ; lssh2 = .TRUE. 
+      CASE ( '-xtra' ) ; lxtra = .TRUE.  ; nvar = 3  ! more outputs
       CASE ( '-full' ) ; lfull = .TRUE. 
       CASE DEFAULT     
          ij = ij + 1
@@ -107,6 +113,7 @@ PROGRAM cdfbotpressure
       END SELECT
    END DO
    CALL SetGlobalAtt(cglobal)
+   ALLOCATE ( ipk(nvar), id_varout(nvar), stypvar(nvar) )
 
    ! Security check
    lchk = chkfile ( cf_in   )
@@ -150,16 +157,40 @@ PROGRAM cdfbotpressure
    stypvar(1)%valid_max         =  1.e15
    stypvar(1)%clong_name        = 'Bottom Pressure'
    stypvar(1)%cshort_name       = 'sobotpres'
+   stypvar(1)%cprecision         = 'r8'
    stypvar(1)%conline_operation = 'N/A'
    stypvar(1)%caxis             = 'TYX'
 
+   IF ( lxtra ) THEN
+      stypvar(2)%cname             = 'sossheig'
+      stypvar(2)%cunits            = 'm'
+      stypvar(2)%rmissing_value    =  0.
+      stypvar(2)%valid_min         = -10.
+      stypvar(2)%valid_max         =  10.
+      stypvar(2)%clong_name        = 'Sea Surface Height'
+      stypvar(2)%cshort_name       = 'sossheig'
+      stypvar(2)%conline_operation = 'N/A'
+      stypvar(2)%caxis             = 'TYX'
+
+      stypvar(3)%cname             = 'sosshpre'
+      stypvar(3)%cunits            = 'Pascal'
+      stypvar(3)%rmissing_value    =  0.
+      stypvar(3)%valid_min         = -100000.
+      stypvar(3)%valid_max         =  100000.
+      stypvar(3)%clong_name        = 'Pressure due to SSH'
+      stypvar(3)%cshort_name       = 'sosshpre'
+      stypvar(3)%cprecision         = 'r8'
+      stypvar(3)%conline_operation = 'N/A'
+      stypvar(3)%caxis             = 'TYX'
+   ENDIF
+
    ! Initialize output file
    gdepw(:) = getvare3(cn_fzgr, cn_gdepw, npk )
    e31d(:)  = getvare3(cn_fzgr, cn_ve3t,  npk )
 
-   ncout = create      (cf_out, cf_in, npiglo, npjglo, 1                    )
-   ierr  = createvar   (ncout, stypvar, 1, ipk, id_varout, cdglobal=cglobal )
-   ierr  = putheadervar(ncout, cf_in,   npiglo, npjglo, 1                   )
+   ncout = create      (cf_out, cf_in, npiglo, npjglo, 1                       )
+   ierr  = createvar   (ncout, stypvar, nvar, ipk, id_varout, cdglobal=cglobal )
+   ierr  = putheadervar(ncout, cf_in,   npiglo, npjglo, 1                      )
 
    tim   = getvar1d    (cf_in, cn_vtimec, npt     )
    ierr  = putvar1d    (ncout, tim,       npt, 'T')
@@ -170,6 +201,10 @@ PROGRAM cdfbotpressure
       IF ( lssh ) THEN
         zt(:,:)       = getvar(cf_in, cn_sossheig, 1, npiglo, npjglo, ktime=jt )
         dl_psurf(:,:) = pp_grav * pp_rau0 * zt(:,:)
+        IF (lxtra ) THEN
+           ierr = putvar(ncout, id_varout(2) ,zt            , 1, npiglo, npjglo, ktime=jt)
+           ierr = putvar(ncout, id_varout(3) ,dl_psurf,       1, npiglo, npjglo, ktime=jt)
+        ENDIF
       ELSE IF ( lssh2 ) THEN 
          zt(:,:)    = getvar(cf_in,   cn_votemper, 1, npiglo, npjglo, ktime=jt )
          zs(:,:)    = getvar(cf_in,   cn_vosaline, 1, npiglo, npjglo, ktime=jt )
@@ -179,6 +214,10 @@ PROGRAM cdfbotpressure
          !  CAUTION : hdept is used for reading SSH in the next line
          hdept(:,:)   = getvar(cf_in, cn_sossheig, 1, npiglo, npjglo, ktime=jt )
         dl_psurf(:,:) = pp_grav * dl_sigi * hdept(:,:)
+        IF (lxtra ) THEN
+           ierr = putvar(ncout, id_varout(2) ,hdept         , 1, npiglo, npjglo, ktime=jt)
+           ierr = putvar(ncout, id_varout(3) ,dl_psurf,       1, npiglo, npjglo, ktime=jt)
+        ENDIF
       ELSE
         dl_psurf(:,:)=0.d0
       ENDIF
diff --git a/cdfbottom.f90 b/src/cdfbottom.f90
similarity index 100%
rename from cdfbottom.f90
rename to src/cdfbottom.f90
diff --git a/cdfbottomsig.f90 b/src/cdfbottomsig.f90
similarity index 88%
rename from cdfbottomsig.f90
rename to src/cdfbottomsig.f90
index f79601d..6519473 100644
--- a/cdfbottomsig.f90
+++ b/src/cdfbottomsig.f90
@@ -49,7 +49,8 @@ PROGRAM cdfbottomsig
 
   TYPE (variable), DIMENSION(1)              :: stypvar        ! structure for attributes
 
-  LOGICAL                                    :: lsigi=.FALSE.  ! flag for sigma-i computation
+  LOGICAL                                    :: lsigi  =.FALSE.! flag for sigma-i computation
+  LOGICAL                                    :: lsigntr=.FALSE.! flag for sigma-Neutral computation
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
@@ -69,6 +70,8 @@ PROGRAM cdfbottomsig
      PRINT *,'      '
      PRINT *,'     OPTIONS :'
      PRINT *,'       [zref] : depth reference for potential density'
+     PRINT *,'              keyword ''ntr'' can also be specified, which indicates that we'
+     PRINT *,'              will use neutral density'
      PRINT *,'             If not given assume sigma-0'
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
@@ -77,6 +80,7 @@ PROGRAM cdfbottomsig
      PRINT *,'     OUTPUT : '
      PRINT *,'       netcdf file : ', TRIM(cf_out) 
      PRINT *,'         variables : sobotsig0 or sobotsigi ( kg/m3 - 1000 )' 
+     PRINT *,'                     or sobotsigntr (kg/m3)'
      STOP
   ENDIF
 
@@ -86,10 +90,18 @@ PROGRAM cdfbottomsig
   IF ( chkfile(cf_tfil) ) STOP ! missing file
 
   IF ( narg == 2 ) THEN
-     lsigi = .TRUE.
-     CALL getarg (2, cldum) ; READ(cldum,*) zref
-     cv_sig = 'sobotsigi'
-     WRITE(cref,'("_refered_to_",i4.4,"_m")') NINT(zref)
+     CALL getarg (2, cldum) 
+      SELECT CASE ( cldum )
+      CASE ('NTR', 'ntr', 'Ntr' ) ! Neutral density will be used
+         lsigntr = .TRUE.
+         cv_sig = 'sobotsigntr'
+         WRITE(cref,'("_Neutral")')
+      CASE DEFAULT                ! Argument is a depth for sig-i
+         lsigi = .TRUE.
+         READ(cldum,*) zref
+         cv_sig = 'sobotsigi'
+         WRITE(cref,'("_refered_to_",i4.4,"_m")') NINT(zref)
+      END SELECT
   ENDIF
 
   npiglo = getdim (cf_tfil,cn_x)
@@ -143,11 +155,14 @@ PROGRAM cdfbottomsig
      
      IF (lsigi ) THEN
         zsig(:,:) = sigmai ( ztemp, zsal, zref, npiglo, npjglo ) * zmask(:,:)
+     ELSE IF (lsigntr ) THEN
+        zsig(:,:) = sigmantr (ztemp, zsal,      npiglo, npjglo )* zmask(:,:)
      ELSE
         zsig(:,:) = sigma0 ( ztemp, zsal,       npiglo, npjglo ) * zmask(:,:)
      ENDIF
 
 
+
      zsigmn=minval(zsig(2:npiglo-1,2:npjglo-1), zmask(2:npiglo-1,2:npjglo-1)==1)
      zsigmx=maxval(zsig(2:npiglo-1,2:npjglo-1), zmask(2:npiglo-1,2:npjglo-1)==1)
      ismin= minloc(zsig(2:npiglo-1,2:npjglo-1), zmask(2:npiglo-1,2:npjglo-1)==1)
diff --git a/cdfbti.f90 b/src/cdfbti.f90
similarity index 100%
rename from cdfbti.f90
rename to src/cdfbti.f90
diff --git a/src/cdfbuoyflx.f90 b/src/cdfbuoyflx.f90
new file mode 100644
index 0000000..efc4b35
--- /dev/null
+++ b/src/cdfbuoyflx.f90
@@ -0,0 +1,426 @@
+PROGRAM cdfbuoyflx
+  !!======================================================================
+  !!                     ***  PROGRAM  cdfbuoyflx  ***
+  !!=====================================================================
+  !!  ** Purpose :  Produce a file with the water flux separated into 4 components:
+  !!                E (evap), P (precip), R (runoff), dmp (sssdmp).
+  !!                The total water flux is E -P -R + dmp. Units in this program
+  !!                are mm/days.  (Up to that it is the same than cdfwflx)
+  !!
+  !!                It also produces un the same file the component of the heat flux
+  !!                Latent Heat FLux, Sensible Heat flux, Long Wave HF, Short Wave HF,
+  !!                Net HF
+  !!
+  !!                Buoyancy fluxes are also computed, as a net value but also with the
+  !!                contribution of each term.
+  !!
+  !!  ** Method  : Evap is computed from the latent heat flux : evap=-qla/Lv
+  !!               Runoff is read from the climatological input file
+  !!               dmp is read from the file (sowafldp)
+  !!               Precip is then computed as the difference between the
+  !!               total water flux (sowaflup) and the E-R+dmp. In the high latitudes
+  !!               this precip includes the effect of snow (storage/melting). Therefore
+  !!               it may differ slightly from the input precip file.
+  !!
+  !!               Heat fluxes are directly copied from the gridT files, same name, same units
+  !!               We also add sst and SSS for convenience.
+  !!
+  !!               Buoyancy fluxes are also computed as :
+  !!                  BF = g/rho ( alpha x TF  - beta x SF ) 
+  !!                       (TF = thermal part, SF = haline part )
+  !!                  TF = Qnet/cp
+  !!                  SF = rho x (E-P) x SSS
+  !!  ** Reference :
+  !!              Atmosphere, Ocean and Climate Dynamics: An Introductory Text. By John Marshall,
+  !!              R. Alan Plumb ( Academic Press, 2008 ) Eq. 11.4 p 225. 
+  !!
+  !! History : 2.1  : 01/2008  : J.M. Molines : Original code
+  !!           3.0  : 12/2010  : J.M. Molines : Doctor norm + Lic.
+  !!           3.0  : 09/2015  : J.M. Molines : add nc4 capabilities, optional output file
+  !!                                            short output,
+  !!                                            different management of read fluxes (XIOS ...)
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE eos
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id$
+  !! Copyright (c) 2010, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)                           :: np_varout=25
+  INTEGER(KIND=4)                           :: ncout, ierr
+  INTEGER(KIND=4)                           :: jt                                ! dummy loop index
+  INTEGER(KIND=4)                           :: narg, iargc, ijarg                ! command line 
+  INTEGER(KIND=4)                           :: npiglo, npjglo, npt               ! size of the domain
+  INTEGER(KIND=4), ALLOCATABLE, DIMENSION(:):: ipk, id_varout  
+
+  ! Physical constants
+  REAL(KIND=4)                              :: Lv = 2.5e6                        ! latent HF <--> evap conversion
+  REAL(KIND=4)                              :: Cp = 4000.                        ! specific heat of water 
+  REAL(KIND=4)                              :: Rho = 1026.                       ! reference density
+  REAL(KIND=4)                              :: Grav = 9.81                       ! Gravity
+
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim, zdep                         ! time counter, deptht
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zmask, zcoefq, zcoefw             ! work array
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zalbet, zbeta                     ! work array
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: evap, precip, runoff, wdmp, wnet  ! water flux components
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: wice, precip_runoff               ! water flux components
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: qlat, qsb, qlw, qsw, qnet         ! heat flux components
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: b_evap, b_precip, b_runoff        ! BF water flux components
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: b_wdmp, bw_net                    ! BF water flux components
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: b_qlat, b_qsb, b_qlw              ! BF heat flux components
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: b_qsw , bh_net                    ! BF heat flux components
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zsst, zsss, buoyancy_fl           ! Total buoyancy flux
+
+  CHARACTER(LEN=256)                        :: cf_tfil ,cf_flxfil, cf_rnfil      ! input file gridT, flx and runoff
+  CHARACTER(LEN=256)                        :: cf_out='buoyflx.nc'               ! output file
+  CHARACTER(LEN=256)                        :: cldum                             ! dummy character variable
+  CHARACTER(LEN=256)                        :: cv_sss                            ! Actual name for SSS
+  CHARACTER(LEN=256)                        :: cv_sst                            ! Actual name for SST
+
+  TYPE(variable), ALLOCATABLE, DIMENSION(:) :: stypvar                           ! structure for attributes
+
+  LOGICAL                                   :: lchk =.false.                     ! flag for missing files
+  LOGICAL                                   :: lnc4 =.false.                     ! flag for netcdf4 output
+  LOGICAL                                   :: lsho =.false.                     ! flag for short output
+  !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  !!  Read command line and output usage message if not compliant.
+  narg= iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage : cdfbuoyflx  -t T-file [-r RNF-file] [-f FLX-file ] [-sss SSS-name]'
+     PRINT *,'     ... [-sst SST-name] [-nc4] [-o output_file]  [-short ]'
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'       Compute (or read) the heat and water fluxes components.'
+     PRINT *,'       Compute (or read) the net heat and water fluxes.'
+     PRINT *,'       Compute the buoyancy heat and water fluxes components.'
+     PRINT *,'       Compute the net buoyancy fluxes.'
+     PRINT *,'       Save sss and sst. '
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       -t T-file   : netcdf file with temperature and salinity '
+     PRINT *,'      '
+     PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'       [ -r RNF-file ] : Specify a run-off file if runoff not in T-file '
+     PRINT *,'                         nor in FLX-file'
+     PRINT *,'       [ -f FLX-file ] : Use this option if fluxes are not saved in gridT files'
+     PRINT *,'       [ -sss SSS-name ] : Use this option if SSS variable name in T-file '
+     PRINT *,'                          differ from ',TRIM(cn_vosaline)
+     PRINT *,'       [ -sst SST-name ] : Use this option if SST variable name in T-file '
+     PRINT *,'                          differ from ',TRIM(cn_votemper)
+     PRINT *,'       [ -nc4 ] Use netcdf4 output with chunking and deflation level 1'
+     PRINT *,'               This option is effective only if cdftools are compiled with'
+     PRINT *,'               a netcdf library supporting chunking and deflation.'
+     PRINT *,'       [ -o output_file ] Default is ', TRIM(cf_out)
+     PRINT *,'       [ -short ] With this option only save the buoyancy flux without '
+     PRINT *,'                  all the components of the flux.'
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'        none'
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file : ', TRIM(cf_out) 
+     PRINT *,'         variables : 25 variables (2D) or 1 variable in case of -short option'
+     PRINT *,'      '
+     PRINT *,'     SEE ALSO :'
+     PRINT *,'      '
+     PRINT *,'      '
+     STOP
+  ENDIF
+  ijarg   = 1
+  cf_flxfil='none'
+  cf_rnfil='none'
+  cv_sss=cn_vosaline
+  cv_sst=cn_votemper
+
+  DO   WHILE ( ijarg <= narg ) 
+     CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1
+     SELECT CASE ( cldum )
+     CASE ( '-f' )     ! specify  flx files
+        CALL getarg (ijarg, cf_flxfil) ; ijarg = ijarg + 1
+        lchk = lchk .OR. chkfile (cf_flxfil)
+     CASE ( '-t' )     ! specify  T files
+        CALL getarg (ijarg, cf_tfil) ; ijarg = ijarg + 1
+        lchk = lchk .OR. chkfile (cf_tfil  )
+     CASE ( '-r' )     ! specify  runoff files
+        CALL getarg (ijarg, cf_rnfil) ; ijarg = ijarg + 1
+        lchk = lchk .OR. chkfile (cf_rnfil )
+     CASE ( '-sss' )     ! specify  runoff files
+        CALL getarg (ijarg, cv_sss) ; ijarg = ijarg + 1
+     CASE ( '-sst' )     ! specify  runoff files
+        CALL getarg (ijarg, cv_sst) ; ijarg = ijarg + 1
+     CASE ( '-nc4' )   !  allow chunking and deflation on output
+        lnc4 = .true.
+     CASE ( '-o' )     ! specify  output files
+        CALL getarg (ijarg, cf_out) ; ijarg = ijarg + 1
+     CASE ( '-short' ) ! use short output ( only buoyancy fluxes )
+        lsho = .true. ; np_varout = 1
+     CASE DEFAULT
+        PRINT *, " Option ", TRIM(cldum)," not supported "
+        STOP
+     END SELECT
+  ENDDO
+  IF (lchk ) STOP ! missing files
+
+  IF ( cf_flxfil == 'none' ) THEN
+    cf_flxfil = cf_tfil
+  ENDIF
+  ! If no runoff file specified, assume that run off are in flx file [ which must be read by the way ... ]
+  IF ( cf_rnfil == 'none' ) THEN
+    cf_rnfil = cf_flxfil
+  ENDIF
+
+  npiglo = getdim (cf_tfil,cn_x)
+  npjglo = getdim (cf_tfil,cn_y)
+  npt    = getdim (cf_tfil,cn_t)
+
+  PRINT *, 'npiglo =', npiglo
+  PRINT *, 'npjglo =', npjglo
+  PRINT *, 'npt    =', npt
+
+  CALL CreateOutput
+
+  ! always allocated
+  ALLOCATE ( zmask(npiglo,npjglo), wnet(npiglo,npjglo), zalbet(npiglo,npjglo), zbeta(npiglo, npjglo) )
+  ALLOCATE ( zcoefq(npiglo,npjglo), zcoefw(npiglo,npjglo), qnet(npiglo,npjglo) )
+  ALLOCATE ( bw_net(npiglo,npjglo) ,bh_net(npiglo,npjglo)) 
+  ALLOCATE ( buoyancy_fl(npiglo,npjglo), zsst(npiglo,npjglo), zsss(npiglo,npjglo) )
+
+  ! allocated only for full output
+  IF ( .NOT. lsho ) THEN
+  ALLOCATE ( evap(npiglo,npjglo), precip(npiglo,npjglo), runoff(npiglo,npjglo), wdmp(npiglo,npjglo) )
+  ALLOCATE ( wice(npiglo,npjglo), precip_runoff(npiglo,npjglo) )
+  ALLOCATE ( qlat(npiglo,npjglo), qsb(npiglo,npjglo), qlw(npiglo,npjglo), qsw(npiglo,npjglo) )
+  ALLOCATE ( b_evap(npiglo,npjglo), b_precip(npiglo,npjglo), b_runoff(npiglo,npjglo), b_wdmp(npiglo,npjglo) ) 
+  ALLOCATE ( b_qlat(npiglo,npjglo), b_qsb(npiglo,npjglo),    b_qlw(npiglo,npjglo),    b_qsw(npiglo,npjglo)  )
+  ENDIF
+
+  DO jt = 1, npt
+     ! read sss for masking purpose and sst
+     zsss(:,:) = getvar(cf_tfil, cv_sss, 1, npiglo, npjglo, ktime=jt)
+     zmask=1. ; WHERE ( zsss == 0 ) zmask=0.
+     zsst(:,:) = getvar(cf_tfil, cv_sst, 1, npiglo, npjglo, ktime=jt)
+
+     ! total water flux (emps)
+     wnet(:,:) = getvar(cf_flxfil, cn_sowaflup, 1, npiglo, npjglo, ktime=jt )*86400.*zmask(:,:)          ! mm/days
+     qnet(:,:)=  getvar(cf_flxfil, cn_sohefldo, 1, npiglo, npjglo, ktime=jt )*zmask(:,:)    ! W/m2 
+
+     ! buoyancy flux
+     zalbet(:,:)= albet ( zsst, zsss, 0., npiglo, npjglo)
+     zbeta (:,:)= beta  ( zsst, zsss, 0., npiglo, npjglo)
+     zcoefq(:,:)= Grav/Rho *( zbeta * zalbet /Cp ) * 1.e6
+     zcoefw(:,:)= Grav* zbeta * zsss / 86400. /1000 * 1.e6   ! division by 86400 and 1000 to get back water fluxes in m/s
+
+     buoyancy_fl=0. ; bh_net=0. ; bw_net=0.
+     WHERE ( zmask == 1 ) 
+        bh_net(:,:)= zcoefq * qnet
+        bw_net(:,:)= zcoefw * wnet
+        buoyancy_fl(:,:) = ( bh_net - bw_net ) 
+     END WHERE
+
+     IF ( .NOT. lsho ) THEN
+     ! Evap : 
+     qlat(:,:)= getvar(cf_flxfil, cn_solhflup, 1, npiglo, npjglo, ktime=jt) *zmask(:,:)    ! W/m2 
+     evap(:,:)= -1.* qlat(:,:) /Lv*86400. *zmask(:,:)                                    ! mm/days
+
+     ! Wdmp
+     wdmp(:,:)= getvar(cf_flxfil, cn_sowafldp, 1, npiglo, npjglo, ktime=jt)*86400.*zmask(:,:) ! mm/days
+
+     ! Runoff  ! take care : not a model output (time_counter may disagree ... jmm
+     runoff(:,:)= getvar(cf_rnfil, 'sorunoff', 1, npiglo, npjglo)*86400.*zmask(:,:)         ! mm/days
+
+     ! fsalt = contribution of ice freezing and melting to salinity ( + = freezing, - = melting )Q
+     wice(:,:) = getvar(cf_flxfil, cn_iowaflup, 1, npiglo, npjglo, ktime=jt )*86400.*zmask(:,:)          ! mm/days
+
+     ! Precip:
+     precip(:,:)= evap(:,:)-runoff(:,:)+wdmp(:,:)-wnet(:,:)+wice(:,:)                     ! mm/day
+
+     ! Precip+runoff : (as a whole ) (interpolated on line)
+     precip_runoff(:,:)= evap(:,:)+wdmp(:,:)-wnet(:,:)+wice(:,:)                          ! mm/day
+
+     ! other heat fluxes
+     qsb(:,:)= getvar(cf_flxfil, cn_sosbhfup,  1, npiglo, npjglo, ktime = jt )*zmask(:,:)    ! W/m2 
+     qlw(:,:)= getvar(cf_flxfil, cn_solwfldo,  1, npiglo, npjglo, ktime = jt )*zmask(:,:)    ! W/m2 
+     qsw(:,:)= getvar(cf_flxfil, cn_soshfldo,  1, npiglo, npjglo, ktime = jt )*zmask(:,:)    ! W/m2 
+
+
+     b_qlat=0.  ; b_qlw=0.    ; b_qsw=0.   ; b_qsb=0.
+     b_evap=0.  ; b_precip=0. ; b_wdmp=0.  ; b_runoff=0.
+
+     WHERE (zsss /= 0 ) 
+        b_qlat(:,:)= zcoefq * qlat
+        b_qlw (:,:)= zcoefq * qlw
+        b_qsw (:,:)= zcoefq * qsw
+        b_qsb (:,:)= zcoefq * qsb
+
+        b_evap(:,:)= zcoefw * evap
+        b_precip(:,:)= -zcoefw * precip
+        b_runoff(:,:)= -zcoefw * runoff
+        b_wdmp(:,:)= zcoefw * wdmp
+
+        !    buoyancy_fl(:,:) = zcoefq * qnet +zcoefw * wnet
+     END WHERE
+     ENDIF
+
+     ! Write output file
+     IF ( lsho ) THEN
+        ierr = putvar(ncout, id_varout(1),buoyancy_fl, 1,npiglo, npjglo, ktime=jt )
+     ELSE
+        ierr = putvar(ncout, id_varout(1), evap,   1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(2), precip, 1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(3), runoff, 1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(4), wdmp,   1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(5), wnet,   1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(6), wice,   1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(7), precip_runoff,   1,npiglo, npjglo, ktime=jt )
+
+        ierr = putvar(ncout, id_varout(8), qlat,   1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(9), qsb,    1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(10),qlw,    1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(11),qsw,    1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(12),qnet,   1, npiglo, npjglo, ktime=jt )
+
+        ierr = putvar(ncout, id_varout(13),b_evap,  1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(14),b_precip,1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(15),b_runoff,1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(16),b_wdmp,  1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(17),bw_net,  1, npiglo, npjglo, ktime=jt )
+
+        ierr = putvar(ncout, id_varout(18),b_qlat,  1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(19),b_qsb,   1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(20),b_qlw,   1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(21),b_qsw,   1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(22),bh_net,  1, npiglo, npjglo, ktime=jt )
+
+        ierr = putvar(ncout, id_varout(23),buoyancy_fl, 1,npiglo, npjglo, ktime=jt )
+
+        ierr = putvar(ncout, id_varout(24), zsss,  1, npiglo, npjglo, ktime=jt )
+        ierr = putvar(ncout, id_varout(25), zsst,  1, npiglo, npjglo, ktime=jt )
+     ENDIF
+  END DO  ! time loop
+
+  tim  = getvar1d(cf_tfil, cn_vtimec, npt     )
+  ierr = putvar1d(ncout,   tim,       npt, 'T')
+
+  ierr=closeout(ncout)
+
+CONTAINS
+  SUBROUTINE CreateOutput
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE CreateOutput  ***
+    !!
+    !! ** Purpose :  Set up all things required for the output file, create
+    !!               the file and write the header part.
+    !!
+    !! ** Method  :  Use global module variables
+    !!
+    !!----------------------------------------------------------------------
+    INTEGER(KIND=4) :: jv   ! dummy loop index
+    !!----------------------------------------------------------------------
+    ! prepare output variables
+    ALLOCATE (zdep(1), tim(npt) )
+    zdep(1) = 0.
+    ALLOCATE (ipk(np_varout), id_varout(np_varout), stypvar(np_varout) )
+    ipk(:)  = 1  ! all variables ( output are 2D)
+    stypvar%conline_operation = 'N/A'
+    stypvar%caxis             = 'TYX'
+    DO jv = 1, np_varout
+       stypvar(jv)%ichunk = (/npiglo,MAX(1,npjglo/30), 1, 1 /)
+    ENDDO
+
+    IF ( lsho ) THEN
+       ! total buoyancy flux
+       stypvar(1)%cname= 'buoyancy_fl'
+       stypvar(1)%cunits='1e-6 m2/s3'
+       stypvar(1)%rmissing_value=0.
+       stypvar(1)%valid_min= -100.
+       stypvar(1)%valid_max= 100.
+       stypvar(1)%clong_name='buoyancy flux'
+       stypvar(1)%cshort_name='buoyancy_fl'
+    ELSE
+       ! 1--> 7 water fluxes                     ;   ! 8 --> 12    heat fluxes
+       stypvar(1)%cname= 'evap'                  ;  stypvar(8)%cname= 'latent'      
+       stypvar(2)%cname= 'precip'                ;  stypvar(9)%cname= 'sensible'      
+       stypvar(3)%cname= 'runoff'                ;  stypvar(10)%cname= 'longwave'      
+       stypvar(4)%cname= 'sssdmp'                ;  stypvar(11)%cname= 'solar'      
+       stypvar(5)%cname= 'watnet'                ;  stypvar(12)%cname= 'heatnet'      
+       stypvar(6)%cname= 'wice'            
+       stypvar(7)%cname= 'precip_runoff'  
+
+       stypvar(1:7)%cunits='mm/day'              ;  stypvar(8:12)%cunits='W/m2'      
+       stypvar(1:7)%rmissing_value=0.            ;  stypvar(8:12)%rmissing_value=0.      
+       stypvar(1:7)%valid_min= -100.             ;  stypvar(8:12)%valid_min= -500.      
+       stypvar(1:7)%valid_max= 100.              ;  stypvar(8:12)%valid_max= 500.      
+       stypvar(1)%clong_name='Evaporation'       ;  stypvar(8)%clong_name='Latent Heat flux'      
+       stypvar(2)%clong_name='Precipitation'     ;  stypvar(9)%clong_name='Sensible Heat flux'       
+       stypvar(3)%clong_name='Runoff'            ;  stypvar(10)%clong_name='Long Wave Heat flux'      
+       stypvar(4)%clong_name='SSS damping'       ;  stypvar(11)%clong_name='Short Wave Heat flux'
+       stypvar(5)%clong_name='Total water flux'  ;  stypvar(12)%clong_name='Net Heat Flux'      
+       stypvar(6)%clong_name='Ice congelation and melting'  
+       stypvar(7)%clong_name='Precip and runoff together' 
+
+       stypvar(1)%cshort_name='evap'             ;  stypvar(8)%cshort_name='latent'      
+       stypvar(2)%cshort_name='precip'           ;  stypvar(9)%cshort_name='sensible'      
+       stypvar(3)%cshort_name='runoff'           ;  stypvar(10)%cshort_name='longwave'      
+       stypvar(4)%cshort_name='sssdmp'           ;  stypvar(11)%cshort_name='solar'      
+       stypvar(5)%cshort_name='watnet'           ;  stypvar(12)%cshort_name='heatnet'       
+       stypvar(6)%cshort_name='wice'  
+       stypvar(7)%cshort_name='precip_runoff' 
+
+       ! 13--> 17  buoy water fluxes             ;   ! 18 --> 22    buoy heat fluxes
+       stypvar(13)%cname= 'evap_b'               ;  stypvar(18)%cname= 'latent_b'
+       stypvar(14)%cname= 'precip_b'             ;  stypvar(19)%cname= 'sensible_b'
+       stypvar(15)%cname= 'runoff_b'             ;  stypvar(20)%cname= 'longwave_b'
+       stypvar(16)%cname= 'sssdmp_b'             ;  stypvar(21)%cname= 'solar_b'
+       stypvar(17)%cname= 'watnet_b'             ;  stypvar(22)%cname= 'heatnet_b'
+
+       stypvar(13:17)%cunits='1e-6 m2/s3'      ;  stypvar(18:22)%cunits='1e-6 m2/s3'
+       stypvar(13:17)%rmissing_value=0.          ;  stypvar(18:22)%rmissing_value=0.
+       stypvar(13:17)%valid_min= -100.           ;  stypvar(18:22)%valid_min= -500.
+       stypvar(13:17)%valid_max= 100.            ;  stypvar(18:22)%valid_max= 500.
+
+       stypvar(13)%clong_name='buoy flx evap'    ;  stypvar(18)%clong_name='buoy Latent Heat flux'
+       stypvar(14)%clong_name='buoy flx precip'  ;  stypvar(19)%clong_name='buoy Sensible Heat flux'
+       stypvar(15)%clong_name='buoy flx runoff'  ;  stypvar(20)%clong_name='buoy Long Wave Heat flux'
+       stypvar(16)%clong_name='buoy flx damping' ;  stypvar(21)%clong_name='buoy Short Wave Heat flux'
+       stypvar(17)%clong_name='buoy haline flx'  ;  stypvar(22)%clong_name='buoy thermo Flux'
+
+       stypvar(13)%cshort_name='evap_b'          ;  stypvar(18)%cshort_name='latent_b'
+       stypvar(14)%cshort_name='precip_b'        ;  stypvar(19)%cshort_name='sensible_b'
+       stypvar(15)%cshort_name='runoff_b'        ;  stypvar(20)%cshort_name='longwave_b'
+       stypvar(16)%cshort_name='sssdmp_b'        ;  stypvar(21)%cshort_name='solar_b'
+       stypvar(17)%cshort_name='watnet_b'        ;  stypvar(22)%cshort_name='heatnet_b'
+
+       ! total buoyancy flux
+       stypvar(23)%cname= 'buoyancy_fl'
+       stypvar(23)%cunits='1e-6 m2/s3'
+       stypvar(23)%rmissing_value=0.
+       stypvar(23)%valid_min= -100.
+       stypvar(23)%valid_max= 100.
+       stypvar(23)%clong_name='buoyancy flux'
+       stypvar(23)%cshort_name='buoyancy_fl'
+
+       ! SSS                                         ; SST
+       stypvar(24)%cname= 'sss'                      ;   stypvar(25)%cname= 'sst'
+       stypvar(24)%cunits='PSU'                      ;   stypvar(25)%cunits='Celsius'
+       stypvar(24)%rmissing_value=0.                 ;   stypvar(25)%rmissing_value=0.
+       stypvar(24)%valid_min= 0.                     ;   stypvar(25)%valid_min= -2.
+       stypvar(24)%valid_max= 45                     ;   stypvar(25)%valid_max= 45
+       stypvar(24)%clong_name='Sea Surface Salinity' ;   stypvar(25)%clong_name='Sea Surface Temperature'
+       stypvar(24)%cshort_name='sss  '               ;   stypvar(25)%cshort_name='sst'
+    ENDIF
+
+    ncout = create      (cf_out, cf_tfil, npiglo,    npjglo, 1,          ld_nc4=lnc4 )
+    ierr  = createvar   (ncout,  stypvar, np_varout, ipk,    id_varout , ld_nc4=lnc4 )
+    ierr  = putheadervar(ncout,  cf_tfil, npiglo,    npjglo, 1,   pdep=zdep )
+  END SUBROUTINE CreateOutput
+
+
+END PROGRAM cdfbuoyflx
diff --git a/cdfcensus.f90 b/src/cdfcensus.f90
similarity index 100%
rename from cdfcensus.f90
rename to src/cdfcensus.f90
diff --git a/src/cdfchgrid.f90 b/src/cdfchgrid.f90
new file mode 100644
index 0000000..aaa925b
--- /dev/null
+++ b/src/cdfchgrid.f90
@@ -0,0 +1,372 @@
+PROGRAM cdfchgrid
+  !!======================================================================
+  !!                     ***  PROGRAM  cdfchgrid  ***
+  !!======================================================================
+  !!  ** Purpose : Transform an 1442x1021 ORCA025 grid variable into an 
+  !!               4322x3059 ORCA12 grid variable.
+  !!               No interpolation, only copying one grid cell into 9 grid cells.
+  !!
+  !!  ** Method  : Store the result on a 'cdfchgrid.nc' file similar to the input file
+  !!               (except x and y dimension)
+  !!
+  !!  ** Restriction  : Caution for mask coherence !
+  !!                    This tool is only adapted for drowned field
+  !!
+  !! History : 3.0 !  08/2012    A. Lecointre   : Original code with Full Doctor form + Lic.
+  !!----------------------------------------------------------------------
+  !!----------------------------------------------------------------------
+  !!   routines      : description
+  !!   chgrid        : Convert coarser grid into refined grid
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE modutils
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id: cdfchgrid.f90 XXX YYYY-MM-DD MM:MM:SSZ molines $
+  !! Copyright (c) 2010, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)                               :: jk, jt                 ! dummy loop index
+  INTEGER(KIND=4)                               :: ivar,iivar             ! dummy loop index
+  INTEGER(KIND=4)                               :: ierr                   ! working integer
+  INTEGER(KIND=4)                               :: narg, iargc, ijarg     ! argument on line
+  INTEGER(KIND=4)                               :: npiglo, npjglo         ! size of the input domain
+  INTEGER(KIND=4)                               :: npigloout              ! I-size of the output domain
+  INTEGER(KIND=4)                               :: npjgloout              ! J-size of the output domain
+  INTEGER(KIND=4)                               :: npk, npkk, npt          ! size of the domain
+  INTEGER(KIND=4)                               :: nvars                  ! number of variables in the input file
+  INTEGER(KIND=4)                               :: ncout                  ! ncid of output ncdf file
+  INTEGER(KIND=4), DIMENSION(1)                 :: ipk                    ! output variable : number of levels
+  INTEGER(KIND=4), DIMENSION(1)                 :: id_varout              ! ncdf varid's
+
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: v2d                    ! array to read a layer of data 
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: u2d                    ! array onto ORCA12-grid
+  REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: tim                    ! time counter of the file
+  REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: rdep                   ! depth of the file
+
+  CHARACTER(LEN=256)                            :: cf_out='cdfchgrid.nc'  ! output file name
+  CHARACTER(LEN=256)                            :: cf_in                  ! input file name
+  CHARACTER(LEN=256)                            :: cf_ref                 ! reference file for output file
+  CHARACTER(LEN=256)                            :: cv_in                  ! variable name
+  CHARACTER(LEN=256)                            :: cldum                  ! working string
+  CHARACTER(LEN=256)                            :: cv_dep                 ! true name of dep dimension
+  CHARACTER(LEN=256)                            :: cl_trf                 ! conversion key
+  CHARACTER(LEN=256)                            :: cglobal                ! Global attribute with command line
+  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_names               ! array of var name
+
+  TYPE (variable), DIMENSION(:),    ALLOCATABLE :: stypvar                ! structure for variable attribute
+  LOGICAL                                       :: lnc4=.FALSE.           ! flag for nc4 output with chinking and deflation
+  LOGICAL                                       :: ldbg=.FALSE.           ! flag for nc4 output with chinking and deflation
+  !!--------------------------------------------------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  narg = iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage : cdfchgrid -f IN-file -r REF-file -var IN-var [-nc4] [-o OUT-file] [-d]'
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'       Build a new file on a refined grid, from a coarser grid, assuming that'
+     PRINT *,'       the two grids are embedded, with common points (hence an odd scaling '
+     PRINT *,'       factor). Grid characteristics are hard wired in the code. Support for'
+     PRINT *,'       ORCA025 --> ORCA12, eORCA025 --> eORCA12 is actually provided. Hooks '
+     PRINT *,'       are ready in the code for adding new conversion.'
+     PRINT *,'       No interpolation, only copying value of a coarse grid cell, onto '
+     PRINT *,'       scale x scale cells of the output grid (scale is the refinement factor)'
+     PRINT *,'      '
+     PRINT *,'     RESTRICTION :'
+     PRINT *,'       Caution for mask coherence !'
+     PRINT *,'       This tool is only adapted for drowned field'
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       -f IN-file  : input Coarser-grid file'
+     PRINT *,'       -r REF-file : Reference file used for identification of the output grid'
+     PRINT *,'               should be of same geometry than the output file.'
+     PRINT *,'       -var IN-var : input coarser-grid variable to be converted'
+     PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'       -nc4        : use netcdf4 chunking and deflation for the output file'
+     PRINT *,'       -o OUT-file : specify output file name instead of ',TRIM(cf_out)
+     PRINT *,'       -d          : Display some debugging information '
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'       none '
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file : ', TRIM(cf_out)
+     PRINT *,'         variable : same name as in input file'
+     STOP
+  ENDIF
+  !!
+  ijarg = 1
+  ! Read command line
+  DO  WHILE (ijarg <=  narg)
+     CALL getarg(ijarg,cldum) ; ijarg = ijarg + 1
+     SELECT CASE ( cldum )
+     CASE ( '-f' )
+        CALL getarg(ijarg, cf_in) ; ijarg = ijarg + 1
+     CASE ( '-r' )
+        CALL getarg(ijarg, cf_ref) ; ijarg = ijarg + 1
+     CASE ( '-var' )
+        CALL getarg(ijarg,cv_in ) ; ijarg = ijarg + 1
+     CASE ( '-o' )
+        CALL getarg(ijarg,cf_out) ; ijarg = ijarg + 1
+     CASE ( '-nc4' )
+        lnc4 = .TRUE.
+     CASE ( '-d' )
+        ldbg = .TRUE.
+     CASE DEFAULT
+        PRINT *, TRIM(cldum),' : unknown option '
+        STOP
+     END SELECT
+  END DO
+
+  IF ( chkfile(cf_in) .OR. chkfile(cf_ref) ) STOP  ! missing files
+
+  ! get domain dimension from input file
+  npiglo = getdim (cf_in, cn_x)
+  npjglo = getdim (cf_in, cn_y)
+  npk    = getdim (cf_in, cn_z, cdtrue=cv_dep, kstatus=ierr)  ! defautl cn_z is depth
+  npt    = getdim (cf_in, cn_t)
+
+  IF ( npt == 0 ) THEN
+     PRINT *, 'npt is forced to 1'
+     npt = 1
+  ENDIF
+
+  IF ( npk == 0 ) THEN
+    npkk = 1
+  ELSE
+    npkk = npk
+  ENDIF
+
+
+  ! get output domain dimension from reference file
+  npigloout = getdim (cf_ref, cn_x)
+  npjgloout = getdim (cf_ref, cn_y)
+  ! infer convertion key from input/output sizes 
+  cl_trf = 'none'
+
+  ! check input size
+  IF ( npiglo ==  722 .AND. npjglo ==  511 ) cl_trf='05to'   ! ORCA05
+  IF ( npiglo == 1442 .AND. npjglo == 1021 ) cl_trf='025to'  ! ORCA025
+  IF ( npiglo == 1442 .AND. npjglo == 1207 ) cl_trf='e025to' ! eORCA025
+  IF ( npiglo == 4322 .AND. npjglo == 3059 ) cl_trf='12to'   ! ORCA12
+  IF ( npiglo == 4322 .AND. npjglo == 3606 ) cl_trf='e12to'  ! eORCA12
+  ! check output size
+  IF ( npigloout ==  722 .AND. npjgloout ==  511 ) cl_trf=TRIM(cl_trf)//'05'
+  IF ( npigloout == 1442 .AND. npjgloout == 1021 ) cl_trf=TRIM(cl_trf)//'025'
+  IF ( npigloout == 1442 .AND. npjgloout == 1207 ) cl_trf=TRIM(cl_trf)//'e025'
+  IF ( npigloout == 4322 .AND. npjgloout == 3059 ) cl_trf=TRIM(cl_trf)//'12'
+  IF ( npigloout == 4322 .AND. npjgloout == 3606 ) cl_trf=TRIM(cl_trf)//'e12'
+
+
+  PRINT *,' INPUT GRID '
+  PRINT *, 'npiglo = ', npiglo
+  PRINT *, 'npjglo = ', npjglo
+  PRINT *, 'npk    = ', npk
+  PRINT *, 'npt    = ', npt
+  PRINT *
+  PRINT *,' OUTPUT GRID '
+  PRINT *, 'npigloout = ', npigloout
+  PRINT *, 'npjgloout = ', npjgloout
+
+  ALLOCATE ( v2d(npiglo+1,npjglo+1) )
+  ALLOCATE ( u2d(npigloout,npjgloout) )
+  ALLOCATE ( tim(npt) )
+  ALLOCATE ( rdep(npkk) )
+
+  ! look for the number of variables in the input file
+  nvars = getnvar(cf_in)
+  ALLOCATE (cv_names(nvars) ,stypvar(nvars))
+  cv_names(:)=getvarname(cf_in,nvars,stypvar)
+
+  ! find the number of variable we are interested in
+  ivar=0
+  DO  WHILE (ivar <   nvars)
+     ivar=ivar+1
+     IF ( cv_names(ivar) == cv_in ) iivar=ivar
+  END DO
+  cglobal="File produced with cdfchgrid "
+  CALL SetGlobalAtt( cglobal, "A" )
+  rdep=getvar1d(cf_in,cv_dep,npkk) 
+
+  ipk(1)=npkk
+  stypvar(iivar)%ichunk = (/npigloout,MAX(1,npjgloout/30),1,1 /)
+
+  ncout = create      (cf_out,   cf_in  , npigloout, npjgloout, npk,   ld_nc4=lnc4  )
+  ierr  = createvar   (ncout   , stypvar(iivar), 1 , ipk  , id_varout, ld_nc4=lnc4, cdglobal=cglobal  )
+  ierr  = putheadervar(ncout,    cf_ref,  npigloout, npjgloout, npk , cdep='deptht', pdep=rdep     )
+
+  ! get time and write time and get deptht and write deptht
+  tim=getvar1d(cf_in,cn_t,npt)    ; ierr=putvar1d(ncout,tim,npt,'T')
+                                    ierr=putvar1d(ncout,rdep,npk,'D')
+
+  PRINT *,' Working with ', TRIM(cv_in), npk
+  DO jt = 1, npt
+     DO jk = 1, npkk
+        v2d(1:npiglo,1:npjglo) = getvar(cf_in, cv_in,  jk, npiglo, npjglo, ktime=jt)
+        ! duplicate last  row and column 
+        v2d(npiglo+1, :) = v2d(npiglo,:)
+        v2d(:,npjglo+1 ) = v2d(:,npjglo)
+        PRINT *,'level ',jk, 'time ',jt
+        CALL chgrid(v2d, u2d, cl_trf)
+        ierr = putvar ( ncout , id_varout(1), REAL(u2d), jk, npigloout, npjgloout, ktime=jt)
+     ENDDO
+  ENDDO
+
+  ierr    = closeout(ncout)
+
+CONTAINS
+
+  SUBROUTINE chgrid (pinvar,poutvar,cd_trf)
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE chgrid  ***
+    !!
+    !! ** Purpose :  This routine just copy input coarser grid
+    !!              onto a finer inbedded grid.
+    !!
+    !! ** Method  :  Each case ( defined by the key cd_trf) is treated
+    !!              separatly 
+    !!----------------------------------------------------------------------
+
+    REAL(KIND=4), DIMENSION(npiglo+1,npjglo+1),   INTENT(in ) :: pinvar
+    REAL(KIND=4), DIMENSION(npigloout,npjgloout), INTENT(out) :: poutvar
+    CHARACTER(LEN=*),                             INTENT(in ) :: cd_trf
+
+    INTEGER(KIND=4)                                           :: jiin,jjin ! dummy loop index
+    INTEGER(KIND=4)                                           :: iiin,ijin ! 
+    INTEGER(KIND=4)                                           :: iiout,ijout !
+    INTEGER(KIND=4)                                           :: ii_offset, ij_offset, iscal
+    INTEGER(KIND=4)                                           :: iicomc,ijcomc,  iicomf,ijcomf
+
+    SELECT CASE (cd_trf)
+    CASE ('025to12')
+       iscal  = 3
+       iicomc = 2
+       ijcomc = 499
+       iicomf = 2
+       ijcomf = 1495
+       CALL filltab( pinvar, poutvar, iscal, iicomc, ijcomc, iicomf,ijcomf)
+       ! force E-W periodicity
+       poutvar(npigloout-1,:)= poutvar(1,:)
+       poutvar(npigloout,  :)= poutvar(2,:)
+
+    CASE ('05to025')
+       ! to do ...
+       PRINT * ,' Conversion ', TRIM(cd_trf), ' not supported yet!'
+    CASE ('05to12')
+       ! to do ...
+       PRINT * ,' Conversion ', TRIM(cd_trf), ' not supported yet!'
+    CASE ('e025toe12')
+       iscal  = 3
+       iicomc = 2
+       ijcomc = 685
+       iicomf = 2
+       ijcomf = 2042
+       CALL filltab( pinvar, poutvar, iscal, iicomc, ijcomc, iicomf,ijcomf)
+       ! force E-W periodicity
+       poutvar(npigloout-1,:)= poutvar(1,:)
+       poutvar(npigloout,  :)= poutvar(2,:)
+       ! 
+    CASE DEFAULT
+       PRINT *, TRIM(cd_trf),'  is not recognized !'
+       PRINT *, 'No conversion will be performed'
+    END SELECT
+
+  END SUBROUTINE chgrid
+
+  SUBROUTINE filltab(  pinvar, poutvar,  kscal, &
+       &         kicomc, kjcomc, kicomf, kjcomf )
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE filltab  ***
+    !!
+    !! ** Purpose :  fill higher resolution poutvar with values from pinvar
+    !!               repeating the values over the iscal x iscale square  
+    !!
+    !!----------------------------------------------------------------------
+    REAL(KIND=4), DIMENSION(npiglo+1,npjglo+1)  , INTENT(in )  :: pinvar
+    REAL(KIND=4), DIMENSION(npigloout,npjgloout), INTENT(out)  :: poutvar
+    INTEGER(KIND=4),                              INTENT(in )  :: kscal
+    INTEGER(KIND=4),                           INTENT(inout )  :: kicomc, kjcomc
+    INTEGER(KIND=4),                           INTENT(inout )  :: kicomf, kjcomf
+    !
+    INTEGER(KIND=4)                           :: jic, jjc, jif, jjf, ji,jj
+    INTEGER(KIND=4)                           :: iiglof, ijglof, ipi,ipj
+    INTEGER(KIND=4)                           :: iiofset, ijofset , iifc, ijfc, iiff, ijff
+    INTEGER(KIND=4)                           :: ii,ij, ii0,ij0,  ii1,ij1
+
+    REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zwvar  ! working array to be cropped out after
+
+    !------------------------------------------------------------------------
+    iiglof=(npiglo+1) * kscal
+    ijglof=(npjglo+1) * kscal
+    ALLOCATE(zwvar(iiglof,ijglof))
+    IF (ldbg) THEN
+       PRINT *,' Size of working array: ', iiglof,ijglof
+       PRINT *,'   last NE corner point ', kscal*(npiglo+1) -kscal/2 ,  kscal*(npjglo+1) -kscal/2
+    ENDIF
+
+    ! fill working fine array with all possible values from coarse array
+    DO jjc = 1, npjglo+1
+       ijfc=kscal * jjc - kscal/2  ! take care : integer division of an odd number
+       DO jic = 1, npiglo+1
+          iifc=kscal * jic - kscal/2  ! take care : integer division of an odd number
+          DO jjf = ijfc - kscal/2, ijfc + kscal/2
+             DO jif = iifc - kscal/2, iifc + kscal/2
+                zwvar(jif,jjf) = pinvar(jic,jjc)
+             ENDDO
+          ENDDO
+       ENDDO
+    ENDDO
+
+    ! crop working array to fit final fine array
+    ! use common point information 
+    ! Compute off set of grid from the inverce of formula : Pf = kscal * Pc + offset 
+    iiofset = kicomf - kscal*kicomc
+    ijofset = kjcomf - kscal*kjcomc
+    ! find the most SW common point for the 2 grids ( brute force!)
+    DO ji=1, npiglo+1
+       ii= ji * kscal + iiofset
+       IF ( ii >= 1) THEN
+          kicomc=ji ; kicomf=ii
+          EXIT
+       ENDIF
+    ENDDO
+
+    DO jj=1, npjglo+1
+       ij= jj * kscal + ijofset
+       IF ( ij >= 1) THEN
+          kjcomc=jj ; kjcomf=ij
+          EXIT
+       ENDIF
+    ENDDO
+    IF ( ldbg ) THEN
+      PRINT *,'   Matching points : '
+      PRINT *,'      coarse : ', kicomc, kjcomc
+      PRINT *,'      fine   : ', kicomf, kjcomf
+   ENDIF
+    ! now do crop zwvar to fit poutvar  iiff,ijff are the index of SW most common point in zwvar
+    iiff = kscal * kicomc - kscal/2 
+    ijff = kscal * kjcomc - kscal/2 
+
+!   ii0=iiff-kicomf +1 ; ii1=MIN(npigloout , ii0+npigloout-1) ; ipi=ii1-ii0+1
+!   ij0=ijff-kjcomf +1 ; ij1=MIN(npjgloout , ij0+npjgloout-1) ; ipj=ij1-ij0+1
+    ii0=iiff-kicomf +1 ; ii1=MIN(iiglof , ii0+npigloout-1) ; ipi=ii1-ii0+1
+    ij0=ijff-kjcomf +1 ; ij1=MIN(ijglof , ij0+npjgloout-1) ; ipj=ij1-ij0+1
+    IF ( ldbg) THEN
+      PRINT *,'  Index limit to crop the array'
+      PRINT *,'     ', ii0,ii1,ij0,ij1
+      PRINT *,'   crop size : ', ipi,ipj
+    ENDIF
+
+    poutvar(:,:) = 999.
+    poutvar(1:ipi,1:ipj) = zwvar(ii0:ii1,ij0:ij1)
+
+    DEALLOCATE (zwvar )
+
+  END SUBROUTINE filltab
+
+END PROGRAM cdfchgrid
diff --git a/cdfclip.f90 b/src/cdfclip.f90
similarity index 95%
rename from cdfclip.f90
rename to src/cdfclip.f90
index 0faf733..3a1840d 100644
--- a/cdfclip.f90
+++ b/src/cdfclip.f90
@@ -59,7 +59,7 @@ PROGRAM cdfclip
 
   narg= iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfclip -f IN-file -zoom imin imax jmin jmax [kmin kmax] '
+     PRINT *,' usage : cdfclip -f IN-file [-o OUT-file] -zoom imin imax jmin jmax [kmin kmax]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
      PRINT *,'       Clip the input file according to the indices given in the'
@@ -75,6 +75,8 @@ PROGRAM cdfclip
      PRINT *,'           meridional or zonal.'
      PRINT *,'      '
      PRINT *,'     OPTIONS :'
+     PRINT *,'       [-o OUT-file ] : use OUT-file instead of ',TRIM(cf_out),' for output file'
+     PRINT *,'               If used, -o option must be used before -zoom argument '
      PRINT *,'       [kmin kmax ] : specify vertical limits for the zoom, in order to reduce'
      PRINT *,'               the extracted area to some levels. Default is to take the whole' 
      PRINT *,'               water column.'
@@ -83,7 +85,7 @@ PROGRAM cdfclip
      PRINT *,'       none' 
      PRINT *,'      '
      PRINT *,'     OUTPUT : '
-     PRINT *,'       netcdf file : ', TRIM(cf_out) 
+     PRINT *,'       netcdf file : ', TRIM(cf_out),' This can be changed using -o option'
      PRINT *,'         variables : same as input variables.'
      STOP
   ENDIF
@@ -99,10 +101,12 @@ PROGRAM cdfclip
        CALL getarg(ijarg,cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) iimax
        CALL getarg(ijarg,cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) ijmin
        CALL getarg(ijarg,cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) ijmax
-       IF ( narg == 9 ) THEN  ! there are kmin kmax optional arguments
+       IF ( ijarg == narg -2  ) THEN  ! there are kmin kmax optional arguments
          CALL getarg(ijarg,cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) ikmin
          CALL getarg(ijarg,cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) ikmax
        ENDIF
+    CASE ('-o')
+       CALL getarg(ijarg,cldum) ; ijarg = ijarg + 1 ; cf_out=cldum
     CASE DEFAULT
        PRINT *,' Unknown option :', TRIM(cldum) ; STOP
     END SELECT
diff --git a/cdfcmp.f90 b/src/cdfcmp.f90
similarity index 99%
rename from cdfcmp.f90
rename to src/cdfcmp.f90
index 05d7d7d..bd98787 100644
--- a/cdfcmp.f90
+++ b/src/cdfcmp.f90
@@ -16,7 +16,7 @@ PROGRAM cdfcmp
   USE modcdfnames
   !!----------------------------------------------------------------------
   !! CDFTOOLS_3.0 , MEOM 2011
-  !! $Id: cdfcmp.f90 XXX YYYY-MM-DD HH:MM:SSZ molines $
+  !! $Id$
   !! Copyright (c) 2010, J.-M. Molines
   !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
   !!----------------------------------------------------------------------
diff --git a/cdfcoastline.f90 b/src/cdfcoastline.f90
similarity index 100%
rename from cdfcoastline.f90
rename to src/cdfcoastline.f90
diff --git a/cdfcofdis.f90 b/src/cdfcofdis.f90
similarity index 88%
rename from cdfcofdis.f90
rename to src/cdfcofdis.f90
index 65f543f..bc9a6ec 100644
--- a/cdfcofdis.f90
+++ b/src/cdfcofdis.f90
@@ -28,7 +28,7 @@ PROGRAM cdfcofdis
   !!----------------------------------------------------------------------
   IMPLICIT NONE
 
-  INTEGER(KIND=4)                           :: jpi, jpj, jpk
+  INTEGER(KIND=4)                           :: jpi, jpj, jpk, npk
   INTEGER(KIND=4)                           :: jpim1, jpjm1, nperio=4
   INTEGER(KIND=4)                           :: narg, iargc, iarg
   INTEGER(KIND=4)                           :: ncout, ierr
@@ -55,16 +55,18 @@ PROGRAM cdfcofdis
   TYPE(variable), DIMENSION(1)              :: stypvar
 
   LOGICAL                                   :: lchk
+  LOGICAL                                   :: lsurf = .false.
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
   !
   narg=iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage :  cdfcofdis mesh_hgr.nc mask.nc gridT.nc [-jperio jperio ]'
+     PRINT *,' usage :  cdfcofdis mesh_hgr.nc mask.nc gridT.nc [-jperio jperio ] [-surf]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
-     PRINT *,'        Compute the distance to the coast and create a file with '
-     PRINT *,'        the ',TRIM(cv_out),' variable, indicating the distance to the coast.'
+     PRINT *,'        Compute the distance to the coast and create a file with the ',TRIM(cv_out)
+     PRINT *,'        variable, indicating the distance to the coast. This computation is done'
+     PRINT *,'        for every model level, unless -surf option is used.'
      PRINT *,'      '
      PRINT *,'     ARGUMENTS :'
      PRINT *,'       HGR-file : name of the mesh_hgr file '
@@ -72,8 +74,9 @@ PROGRAM cdfcofdis
      PRINT *,'       T-file   : netcdf file at T point.'
      PRINT *,'      '
      PRINT *,'     OPTIONS :'
-     PRINT *,'       [ -jperio jperio ] : define the NEMO jperio variable for north fold condition' 
-     PRINT *,'                Default is  4.'
+     PRINT *,'       [ -jperio jperio ] : define the NEMO jperio variable for north fold '
+     PRINT *,'           condition. Default is  4.'
+     PRINT *,'       [ -surf ] : only compute  distance at the surface.'
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'       none' 
@@ -101,6 +104,8 @@ PROGRAM cdfcofdis
     SELECT CASE ( cldum )
     CASE ( '-jperio' ) 
        CALL getarg (iarg,cldum) ; READ(cldum, * ) nperio  ; iarg = iarg + 1
+    CASE ( '-surf' ) 
+       lsurf = .true.
     CASE DEFAULT
        PRINT *,' unknown option : ', TRIM(cldum)
        STOP
@@ -146,7 +151,13 @@ PROGRAM cdfcofdis
   gphif(:,:) = getvar(cn_fhgr,cn_gphif,1,jpi,jpj)
 
   ! prepare file output
-  ipk(1)                       = jpk
+  IF ( lsurf ) THEN
+     npk                       = 1
+  ELSE
+     npk = jpk
+  ENDIF
+
+  ipk(1)                       = npk
   stypvar(1)%cname             = cv_out
   stypvar(1)%cunits            = 'm'
   stypvar(1)%rmissing_value    = 0
@@ -158,15 +169,15 @@ PROGRAM cdfcofdis
   stypvar(1)%caxis             = 'TZYX'
   stypvar(1)%cprecision        = 'r4'
 
-  ncout = create      (cf_out, cf_tfil, jpi, jpj, jpk       )
+  ncout = create      (cf_out, cf_tfil, jpi, jpj, npk       )
   ierr  = createvar   (ncout,  stypvar, 1,   ipk, id_varout )
-  ierr  = putheadervar(ncout,  cf_tfil, jpi, jpj, jpk       )
+  ierr  = putheadervar(ncout,  cf_tfil, jpi, jpj, npk       )
 
-  CALL cofdis
+  CALL cofdis (npk)
   
   CONTAINS
 
-  SUBROUTINE cofdis()
+  SUBROUTINE cofdis(kpk)
     !!----------------------------------------------------------------------
     !!                 ***  ROUTINE cofdis  ***
     !!
@@ -186,6 +197,8 @@ PROGRAM cdfcofdis
     !! ** Action  : - pdct, distance to the coastline (argument)
     !!              - NetCDF file 'dist.coast' 
     !!----------------------------------------------------------------------
+    INTEGER(KIND=4), INTENT(in) ::   kpk                 ! number of level to deal with
+
     INTEGER(KIND=4) ::   ji, jj, jk, jl      ! dummy loop indices
     INTEGER(KIND=4) ::   iju, ijt            ! temporary integers
     INTEGER(KIND=4) ::   icoast, itime
@@ -208,7 +221,7 @@ PROGRAM cdfcofdis
     ! 1. Loop on vertical levels
     ! --------------------------
     !                                             ! ===============
-    DO jk = 1, jpk                                ! Horizontal slab
+    DO jk = 1, kpk                                ! Horizontal slab
        !                                          ! ===============
        PRINT *,'WORKING for level ', jk, nperio
        pdct(:,:) = 0.e0
@@ -216,9 +229,24 @@ PROGRAM cdfcofdis
        !    temp(:,:) = getvar(cbathy,'Bathy_level',1, npiglo, npjglo)
 
        tmask(:,:)=getvar(cn_fmsk,'tmask',jk,jpi,jpj)
-       umask(:,:)=getvar(cn_fmsk,'umask',jk,jpi,jpj)
-       vmask(:,:)=getvar(cn_fmsk,'vmask',jk,jpi,jpj)
-       fmask(:,:)=getvar(cn_fmsk,'fmask',jk,jpi,jpj)
+!      umask(:,:)=getvar(cn_fmsk,'umask',jk,jpi,jpj)
+!      vmask(:,:)=getvar(cn_fmsk,'vmask',jk,jpi,jpj)
+!      fmask(:,:)=getvar(cn_fmsk,'fmask',jk,jpi,jpj)
+       DO jj = 1, jpjm1
+          DO ji = 1, jpim1   ! vector loop
+             umask(ji,jj) = tmask(ji,jj ) * tmask(ji+1,jj  )
+             vmask(ji,jj) = tmask(ji,jj ) * tmask(ji  ,jj+1)
+          END DO
+          DO ji = 1, jpim1      ! NO vector opt.
+             fmask(ji,jj) = tmask(ji,jj  ) * tmask(ji+1,jj  )   &
+                &         * tmask(ji,jj+1) * tmask(ji+1,jj+1)
+          END DO
+       END DO
+       umask(jpi,:)=umask(2,:)
+       vmask(jpi,:)=vmask(2,:)
+       fmask(jpi,:)=fmask(2,:)
+
+
        PRINT *, '    READ masks done.'
        ! Define the coastline points (U, V and F)
        DO jj = 2, jpjm1
diff --git a/cdfcoloc.f90 b/src/cdfcoloc.f90
similarity index 100%
rename from cdfcoloc.f90
rename to src/cdfcoloc.f90
diff --git a/cdfconvert.f90 b/src/cdfconvert.f90
similarity index 100%
rename from cdfconvert.f90
rename to src/cdfconvert.f90
diff --git a/cdfcsp.f90 b/src/cdfcsp.f90
similarity index 100%
rename from cdfcsp.f90
rename to src/cdfcsp.f90
diff --git a/src/cdfcurl.f90 b/src/cdfcurl.f90
new file mode 100644
index 0000000..f5394de
--- /dev/null
+++ b/src/cdfcurl.f90
@@ -0,0 +1,415 @@
+PROGRAM cdfcurl
+  !!======================================================================
+  !!                     ***  PROGRAM  cdfcurl  ***
+  !!=====================================================================
+  !!  ** Purpose : Compute the curl on F-points for given gridU gridV 
+  !!               files and variables
+  !!
+  !!  ** Method  : Use the same algorithm than NEMO
+  !!
+  !! History : 2.1  : 05/2005  : J.M. Molines : Original code
+  !!         : 2.1  : 06/2007  : P. Mathiot   : for use with forcing fields
+  !!           3.0  : 01/2011  : J.M. Molines : Doctor norm + Lic.
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id$
+  !! Copyright (c) 2011, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)                           :: ji, jj, jk, jt     ! dummy loop index
+  INTEGER(KIND=4)                           :: npiglo, npjglo     ! size of the domain
+  INTEGER(KIND=4)                           :: npk, npt           ! size of the domain
+  INTEGER(KIND=4)                           :: nlev               ! number of output levels
+  INTEGER(KIND=4)                           :: narg, iargc        ! browse command line
+  INTEGER(KIND=4)                           :: ijarg              !
+  INTEGER(KIND=4)                           :: ncout, ierr        ! browse command line
+  INTEGER(KIND=4), DIMENSION(1)             :: ipk, id_varout     ! output variable properties
+  INTEGER(KIND=4), DIMENSION(:), ALLOCATABLE :: nilev             ! level to be processed
+
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e2v, e1u, e1f, e2f ! horizontql metrics
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: un, vn             ! velocity field
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zun, zvn           ! working arrays
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: fmask              ! mask
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim, zdep, gdep    ! time counter
+  REAL(KIND=4)                              :: zmask              ! mask at T point for -T option
+
+  REAL(KIND=8)                              :: dl_pi, dl_omega    ! 3.14159... and earth rotation rad/sec
+  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: drotn              ! curl 
+  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dl_rotn            ! curl at T point 
+  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dl_ff              ! Coriolis parameter at F point
+
+  CHARACTER(LEN=256)                        :: cf_ufil, cf_vfil   ! file names
+  CHARACTER(LEN=256)                        :: cf_out = 'curl.nc' ! output file name
+  CHARACTER(LEN=256)                        :: cv_u, cv_v         ! variable names
+  CHARACTER(LEN=256)                        :: cldum              ! dummy string
+
+  TYPE (variable), DIMENSION(1)             :: stypvar            ! structure for attibutes
+
+  LOGICAL                                   :: lforcing = .FALSE. ! forcing flag
+  LOGICAL                                   :: lchk     = .FALSE. ! flag for missing files
+  LOGICAL                                   :: lperio   = .FALSE. ! flag for E-W periodicity
+  LOGICAL                                   :: ltpoint  = .FALSE. ! flag for T-point output
+  LOGICAL                                   :: ldblpr   = .FALSE. ! flag for dble precision output
+  LOGICAL                                   :: lsurf    = .FALSE. ! flag for 1 lev on C grid.
+  LOGICAL                                   :: loverf   = .FALSE. ! flag for 1 lev on C grid.
+  LOGICAL                                   :: lnc4=.false.       ! flag for netcdf4 output with chunking and deflation
+
+  !!----------------------------------------------------------------------
+  CALL ReadCdfNames() 
+
+  narg = iargc()
+  IF ( narg < 5 ) THEN
+     PRINT *,' usage : cdfcurl -u U-file U-var -v V-file V-var -l levlist [-T] [-8]...'
+     PRINT *,'           ... [-surf] [-overf] [-nc4] [-o OUT-file ]'
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'       Compute the curl of a vector field, at a specified level.'  
+     PRINT *,'       If level is specified as 0, assume that the input files are'
+     PRINT *,'       forcing files, presumably on A-grid. In this latter case, the'
+     PRINT *,'       vector field is interpolated on the C-grid. In any case, the'
+     PRINT *,'       curl is computed on the F-point (unless -T option is used).'
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       -u U-file U-var : file and variable name for zonal component'
+     PRINT *,'       -v V-file V-var : file and variable name for meridional component'
+     PRINT *,'       -l levlist    : levels to be processed. If set to 0, assume forcing file'
+     PRINT *,'                in input. Example of recognized syntax :'
+     PRINT *,'                  -l "1,10,30"  or -l "1-20" or even -l "1-3,10-20,30-"'
+     PRINT *,'                  -l  1 . Note that -l "3-" set a levlist from 3 to the bottom'
+     PRINT * 
+     PRINT *,'     OPTIONS :'
+     PRINT *,'       -T : compute curl at T point instead of default F-point'
+     PRINT *,'       -8 : save in double precision instead of standard simple precision.'
+     PRINT *,'       -surf : work with single level C-grid (not forcing)'
+     PRINT *,'       -overf : store the ratio curl/f where f is the coriolis parameter'
+     PRINT *,'       -nc4 : use netcdf4 output with chunking and deflation 1'
+     PRINT *,'       -o OUT-file : specify output file name instead of ',TRIM(cf_out) 
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'        ', TRIM(cn_fhgr)
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file : ', TRIM(cf_out) 
+     PRINT *,'         variables : socurl or socurlt (if -T option), units : s^-1'
+     PRINT *,'            or socurloverf, no units (if -overf option)'
+     STOP
+  ENDIF
+
+  ijarg=1
+  DO WHILE ( ijarg <= narg ) 
+     CALL getarg(ijarg, cldum) ; ijarg=ijarg+1
+     SELECT CASE ( cldum )
+     CASE ('-u')
+        CALL getarg(ijarg, cf_ufil) ; ijarg=ijarg+1
+        CALL getarg(ijarg, cv_u   ) ; ijarg=ijarg+1
+     CASE ('-v')
+        CALL getarg(ijarg, cf_vfil) ; ijarg=ijarg+1
+        CALL getarg(ijarg, cv_v   ) ; ijarg=ijarg+1
+     CASE ('-l')
+        CALL getarg(ijarg, cldum) ; ijarg=ijarg+1 
+        CALL ParseLevel(cldum)  ! fills in array nilev(nlev)
+     CASE ( '-nc4' )
+        lnc4 = .true.
+     CASE ('-T')
+        ltpoint = .true.
+     CASE ('-8')
+        ldblpr = .true.
+     CASE ('-surf')
+        lsurf = .true.
+     CASE ('-overf')
+        loverf = .true.
+     CASE ('-o')
+        CALL getarg(ijarg, cf_out) ; ijarg=ijarg+1
+     CASE DEFAULT
+        PRINT *,  TRIM(cldum), ' : unknown option '
+     END SELECT
+  ENDDO
+
+  lchk = chkfile(cn_fhgr ) .OR. lchk
+  lchk = chkfile(cf_ufil ) .OR. lchk
+  lchk = chkfile(cf_vfil ) .OR. lchk
+  IF ( lchk ) STOP ! missing files
+
+
+  ! define new variables for output
+  stypvar(1)%cname             = 'socurl'
+  IF (ltpoint) stypvar(1)%cname             = 'socurlt'
+  stypvar(1)%cunits            = 's-1'
+  IF (loverf)  stypvar(1)%cname             = 'socurloverf'
+  IF (loverf)  stypvar(1)%cunits            = '-'
+
+  stypvar(1)%cprecision        ='r4'
+  IF ( ldblpr )  stypvar(1)%cprecision     ='r8'
+  stypvar(1)%rmissing_value    = 0.
+  stypvar(1)%valid_min         = -1000.
+  stypvar(1)%valid_max         =  1000.
+  stypvar(1)%clong_name        = 'Relative_Vorticity (curl)'
+  stypvar(1)%cshort_name       = 'socurl'
+  stypvar(1)%conline_operation = 'N/A'
+  stypvar(1)%caxis             = 'TYX'
+
+  ipk(1) = nlev  !  nlevel so far
+
+  npiglo = getdim(cf_ufil,cn_x)
+  npjglo = getdim(cf_ufil,cn_y)
+  npk    = getdim(cf_ufil,cn_z)
+  npt    = getdim(cf_ufil,cn_t) 
+
+  PRINT *, 'npiglo = ',npiglo
+  PRINT *, 'npjglo = ',npjglo
+  PRINT *, 'npk    = ',npk
+  PRINT *, 'npt    = ',npt
+  PRINT *, 'nlev   = ',nlev
+
+  ! choose chunk size for output ... not easy not used if lnc4=.false. but anyway ..
+  stypvar(1)%ichunk=(/npiglo,MAX(1,npjglo/30),1,1 /)
+  print *, stypvar(1)%ichunk
+
+  !test if lev exists
+  IF ( (npk==0) .AND. (nlev > 0) .AND. .NOT. lsurf ) THEN
+     PRINT *, 'Problem : npk = 0 and lev > 0 STOP'
+     PRINT *, '  Use -surf option is dealing with single level file on C grid '
+     STOP
+  END IF
+
+  ! case of 1 level on C-grid
+  IF ( lsurf ) THEN
+     nlev=1
+     IF (ALLOCATED (nilev) ) THEN
+        DEALLOCATE(nilev) 
+     ENDIF
+     ALLOCATE(nilev(nlev) )
+     npk = 1 ; nilev(1) =1 
+  ENDIF
+
+  ! if forcing field 
+  IF ( nilev(1) == 0 .AND. npk==0 ) THEN
+     lforcing=.true.
+     npk = 1 ; nilev(1)=1
+     PRINT *, 'npk =0, assume 1'
+  END IF
+
+
+  IF ( npt==0 ) THEN
+     PRINT *, 'npt=0, assume 1'
+     npt=1
+  END IF
+  ! 
+  DO jk = 1, nlev
+   IF (nilev(jk) >= npk ) THEN
+     nlev=jk
+     EXIT
+   ENDIF
+  ENDDO
+  PRINT *, 'NLEV', nlev
+
+  ! Allocate the memory
+  ALLOCATE ( e1u(npiglo,npjglo) , e1f(npiglo,npjglo) )
+  ALLOCATE ( e2v(npiglo,npjglo) , e2f(npiglo,npjglo) )
+  ALLOCATE ( un(npiglo,npjglo)  , vn(npiglo,npjglo)  )
+  ALLOCATE ( zun(npiglo,npjglo) , zvn(npiglo,npjglo) )
+  ALLOCATE ( drotn(npiglo,npjglo) , fmask(npiglo,npjglo) )
+  ALLOCATE ( tim(npt) )
+  ALLOCATE ( gdep(nlev) , zdep(npk))
+
+  IF ( ltpoint) ALLOCATE (dl_rotn(npiglo,npjglo) )
+
+  e1u =  getvar(cn_fhgr, cn_ve1u, 1, npiglo, npjglo)
+  e1f =  getvar(cn_fhgr, cn_ve1f, 1, npiglo, npjglo)
+  e2v =  getvar(cn_fhgr, cn_ve2v, 1, npiglo, npjglo)
+  e2f =  getvar(cn_fhgr, cn_ve2f, 1, npiglo, npjglo)
+
+  ! use zun and zvn to store f latitude and longitude for output
+  zun = getvar(cn_fhgr, cn_glamf, 1, npiglo, npjglo)
+  zvn = getvar(cn_fhgr, cn_gphif, 1, npiglo, npjglo)
+
+  IF ( loverf ) THEN
+     ALLOCATE (dl_ff(npiglo,npjglo) )
+     dl_pi = acos(-1.d0)
+     dl_omega = 2* dl_pi/86400.d0
+     dl_ff = 2* dl_omega* sin ( zvn*dl_pi/180.d0 ) 
+  ENDIF
+  
+  ! fills in gdep
+  IF ( lforcing .OR. lsurf ) THEN
+     gdep(1)=0.
+  ELSE
+    zdep(:) = getvar1d(cf_ufil, cn_vdepthu, npk )
+    DO jk=1,nlev
+      gdep(jk) = zdep( nilev(jk) )
+    ENDDO
+  ENDIF
+
+
+  ! look for  E-W periodicity
+  IF ( zun(1,1) == zun(npiglo-1,1) ) lperio = .TRUE.
+
+  ! create output fileset
+  ncout = create      (cf_out, cf_ufil, npiglo, npjglo, nlev           , ld_nc4=lnc4)
+  ierr  = createvar   (ncout , stypvar, 1,      ipk,    id_varout      , ld_nc4=lnc4)
+  ierr  = putheadervar(ncout,  cf_ufil, npiglo, npjglo, nlev, pnavlon=zun, pnavlat=zvn, pdep=gdep)
+
+  tim  = getvar1d(cf_ufil, cn_vtimec, npt      )
+  ierr = putvar1d(ncout,   tim,       npt,  'T')
+
+  DO jt=1,npt
+     IF (MOD(jt,100)==0 ) PRINT *, jt,'/',npt
+     DO jk = 1, nlev
+        ! if files are forcing fields
+        zun(:,:) =  getvar(cf_ufil, cv_u, nilev(jk) ,npiglo,npjglo, ktime=jt)
+        zvn(:,:) =  getvar(cf_vfil, cv_v, nilev(jk) ,npiglo,npjglo, ktime=jt)
+
+        IF ( lforcing ) THEN ! for forcing file u and v are on the A grid
+           DO ji=1, npiglo-1
+              un(ji,:) = 0.5*(zun(ji,:) + zun(ji+1,:))
+           END DO
+           !
+           DO jj=1, npjglo-1
+              vn(:,jj) = 0.5*(zvn(:,jj) + zvn(:,jj+1))
+           END DO
+           ! end compute u and v on U and V point
+        ELSE
+           un(:,:) = zun(:,:)
+           vn(:,:) = zvn(:,:)
+        END IF
+
+        ! compute the mask ! must be done every time as we have a level loop now
+        ! might be replaced by reading fmask from mask file
+        !    IF ( jt==1 ) THEN
+        DO jj = 1, npjglo - 1
+           DO ji = 1, npiglo - 1
+              fmask(ji,jj)=0.
+              fmask(ji,jj)= un(ji,jj)*un(ji,jj+1) * vn(ji,jj)*vn(ji+1,jj)
+              IF (fmask(ji,jj) /= 0.) fmask(ji,jj)=1.
+           ENDDO
+        ENDDO
+        !    END IF
+
+        drotn(:,:) = 0.d0
+        DO jj = 1, npjglo -1 
+           DO ji = 1, npiglo -1   ! vector opt.
+              drotn(ji,jj) = (  e2v(ji+1,jj  ) * vn(ji+1,jj  ) - e2v(ji,jj) * vn(ji,jj)    &
+                   &          - e1u(ji  ,jj+1) * un(ji  ,jj+1) + e1u(ji,jj) * un(ji,jj)  ) &
+                   &          * fmask(ji,jj) / ( e1f(ji,jj) * e2f(ji,jj) )
+           END DO
+        END DO
+
+        IF ( lperio ) drotn(npiglo,:) = drotn(2, :)
+        IF ( ltpoint ) THEN
+           dl_rotn(:,:) = 0.d0
+           DO ji = 2, npiglo
+              DO jj = 2, npjglo
+                 zmask = fmask(ji,jj)*fmask(ji,jj-1)*fmask(ji-1,jj)*fmask(ji-1,jj-1)
+                 dl_rotn(ji,jj) = 0.25*( drotn(ji,jj) + drotn(ji,jj-1) + drotn(ji-1,jj) + drotn(ji-1,jj-1) ) * zmask
+              ENDDO
+           ENDDO
+           IF ( lperio ) dl_rotn(1,:) = dl_rotn(npiglo, :)
+           drotn(:,:) = dl_rotn(:,:)
+
+        ENDIF
+        ! write drotn on file at level k and at time jt
+        IF ( loverf ) THEN
+           WHERE (dl_ff /= 0.d0) drotn=drotn/dl_ff
+        ENDIF
+
+        ierr = putvar(ncout, id_varout(1), drotn, nilev(jk), npiglo, npjglo, ktime=jt)
+     ENDDO
+  END DO
+  ierr = closeout(ncout)
+
+CONTAINS
+  SUBROUTINE ParseLevel( cdum )
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE ParsLevel  ***
+    !!
+    !! ** Purpose :  Parse a string representing a level list with no separator
+    !!               or , or - as separator 
+    !!
+    !! ** Method  :   1,3,5 => list = (1,3,5)
+    !!                1-4   => liste = ( 1,2,3,4) 
+    !!                1-4,6-8   => liste = ( 1,2,3,4,6,7,8) 
+    !!                10-      => liste = (10,11,12,...bottom)
+    !!                Allocate and fill nilev array with respective levels
+    !!
+    !!----------------------------------------------------------------------
+    CHARACTER(LEN=*), INTENT (in ) :: cdum
+
+    INTEGER(KIND=4)                 :: jc, jk
+    INTEGER(KIND=4)                 :: ilength, ik1, ik2
+    INTEGER(KIND=4)                 :: icomma, idash, ipos, ipos1
+    INTEGER(KIND=4), DIMENSION(350) :: ilev
+    CHARACTER(LEN=256) :: cldum
+    CHARACTER(LEN=80), DIMENSION(:), ALLOCATABLE :: clblk
+    !!----------------------------------------------------------------------
+    ilength=LEN(TRIM(cdum) )
+
+    ! look for , and -
+    icomma = 0 ; idash = 0
+    DO jc=1,ilength
+       IF ( cdum(jc:jc) == ',' ) THEN
+          icomma = icomma + 1
+       ELSE IF ( cdum(jc:jc) == '-' ) THEN
+          idash = idash + 1
+       ENDIF
+    END DO
+
+    ! no dash nor comma
+    IF (icomma == 0 .AND. idash == 0 ) THEN
+       nlev=1
+       ALLOCATE ( nilev(nlev) )
+       READ(cdum,*) nilev(1)
+       RETURN
+    ENDIF
+    ! look for the number of blocks (between commas)
+    cldum=cdum
+    ALLOCATE (clblk(icomma+1))
+
+    ipos1=1
+    DO jc=1,icomma
+       ipos=INDEX(cldum ,",")
+       clblk(jc)=cldum(1:ipos-1)
+       ipos1=ipos+1
+       cldum=cldum(ipos1:)
+    ENDDO
+    clblk(icomma+1)=cldum
+
+    ! now parse block
+    nlev=0
+    DO jc=1,icomma+1
+       ipos=INDEX(clblk(jc),"-")
+       IF ( ipos == 0 ) THEN
+          nlev=nlev+1
+          READ(clblk(jc),* ) ilev(nlev) 
+       ELSE IF ( ipos == LEN(TRIM((clblk(jc)))) ) THEN
+          READ(clblk(jc)(1:ipos-1),*) ik1
+          ik2=300  ! use 300 as a maximum mean while we wait for npk
+          PRINT *,' BINGO !', ik1, ik2
+          DO jk=ik1,ik2
+             nlev=nlev+1
+             ilev(nlev)=jk
+          ENDDO
+       ELSE
+          READ(clblk(jc)(1:ipos-1),*) ik1
+          READ(clblk(jc)(ipos+1: ),*) ik2
+          DO jk=ik1,ik2
+             nlev=nlev+1
+             ilev(nlev)=jk
+          ENDDO
+       ENDIF
+    ENDDO
+    ALLOCATE (nilev(nlev) )
+    nilev(:)=ilev(1:nlev)
+
+    DEALLOCATE( clblk)
+
+
+  END SUBROUTINE ParseLevel
+
+END PROGRAM cdfcurl
+
+
diff --git a/src/cdfdegradt.f90 b/src/cdfdegradt.f90
new file mode 100644
index 0000000..3d773fb
--- /dev/null
+++ b/src/cdfdegradt.f90
@@ -0,0 +1,321 @@
+PROGRAM cdfdegradt
+  !!======================================================================
+  !!                   ***  PROGRAM  cdfdegradt  ***
+  !!=====================================================================
+  !!  ** Purpose : Degrade horizontal resolution of NEMO gridT output
+  !!
+  !!  ** Method  : Degradation procedure ensuring the conservation
+  !!               of tracers fluxes, preserving the tracer budget 
+  !!
+  !! History : 1.0 : 11/2011  : X. Meunier : Original code
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id$
+  !! Copyright (c) 2011, 
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: nflsdc           ! array for fluid sub-domain counter
+  INTEGER(KIND=4), DIMENSION(:),     ALLOCATABLE :: ipk, id_varout, id_varout2
+  INTEGER(KIND=4)                           :: ji, jj, jk, jt     ! dummy loop index
+  INTEGER(KIND=4)                           :: jri, jrj           ! dummy loop index
+  INTEGER(KIND=4)                           :: ik, ii, ij         !
+  INTEGER(KIND=4)                           :: ix, iy             !
+  INTEGER(KIND=4)                           :: ierr               ! error status
+  INTEGER(KIND=4)                           :: nri=1, nrj=1       ! scale degrading factor along i and j  
+  INTEGER(KIND=4)                           :: iimin=2            ! indice from where the filtering begins
+  INTEGER(KIND=4)                           :: ijmin=2            ! indice from where the filtering begins
+  INTEGER(KIND=4)                           :: narg, iargc, ijarg ! browse command line
+  INTEGER(KIND=4)                           :: npiglo, npjglo     ! size of the domain
+  INTEGER(KIND=4)                           :: npk, npt           ! size of the domain
+  INTEGER(KIND=4)                           :: ncout, ncout2      ! ncid of output file
+  INTEGER(KIND=4)                           :: msks               ! mask sum on each coarse cells
+  INTEGER(KIND=4)                           :: nvpk               ! vertical levels in working variable
+  INTEGER(KIND=4)                           :: ikx=1, iky=1       ! dims of netcdf output file
+
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zmask              ! 2D mask at current level
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: glamf, gphif       ! lon, lat
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e1, e2, e3, zv     ! metrics, variable
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: rdumlon, rdumlat   ! dummy lon/lat for output file
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: rdummymean         ! array for mean value on output file
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim                ! time counter
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: gdep               ! depth 
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: zdep               ! depth of the whole vertical levels
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: e31d               ! 1d vertical spacing
+  REAL(KIND=4)                              :: zspval             ! missing value
+
+  REAL(KIND=8)                              :: dvol, dsum, dsurf  ! cumulated values
+  REAL(KIND=8)                              :: dvol2d, dsum2d     !
+
+  CHARACTER(LEN=256)                        :: cf_tfil            ! input filename
+  CHARACTER(LEN=256)                        :: cf_ncout,cf_ncout2 ! output file name
+  !
+  CHARACTER(LEN=256)                        :: cv_nam             ! current variable name
+  CHARACTER(LEN=20)                         :: cv_e1, cv_e2       ! horizontal metrics names
+  CHARACTER(LEN=20)                         :: cv_e3, cv_e31d     ! vertical metrics names
+  CHARACTER(LEN=20)                         :: cv_msk             ! mask variable name
+  CHARACTER(LEN=256)                        :: cv_dep             ! deptht name
+  !
+  CHARACTER(LEN=256)                        :: clunits            ! attribute of output file : units
+  CHARACTER(LEN=256)                        :: cldum              ! dummy char variable
+  CHARACTER(LEN=256)                        :: cllong_name        !     "      long name
+  CHARACTER(LEN=256)                        :: cglobal            !     "      global 
+  CHARACTER(LEN=256)                        :: clshort_name       !     "      short name
+
+  TYPE(variable), DIMENSION(:), ALLOCATABLE :: stypvar            ! structure of output
+  TYPE(variable), DIMENSION(:), ALLOCATABLE :: stypvar2           ! structure of sub-domain counter output
+
+  LOGICAL                                   :: lfull     = .false.! full step  flag
+  LOGICAL                                   :: lchk               ! flag for missing files
+ 
+ !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  narg = iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage : cdfdegradt IN-Tfile IN-var ri rj [i0 j0]'
+     PRINT *,'       ... [-full]'
+     PRINT *,'       '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'       Degrad the horizontal resolution of NEMO T-grid ouput,       ' 
+     PRINT *,'       for each z-level and time step, with a ratio of ri along     '
+     PRINT *,'       x direction and rj along y direction. If specified, the input'
+     PRINT *,'       grid is considered starting from the indices i0 and j0.      ' 
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       IN-Tfile  : netcdf T-file.' 
+     PRINT *,'       IN-var    : name of netcdf variable to work with' 
+     PRINT *,'       ri        : degradation ratio for x-direction   ' 
+     PRINT *,'       rj        : degradation ratio for y-direction   ' 
+     PRINT *,'      '
+     PRINT *,'     OPTIONS : '
+     PRINT *,'       [i0 j0] : spatial indices from where starting the procedure   '
+     PRINT *,'                 of degradation.                                    ' 
+     PRINT *,'       [-full] : flag for full steps grid, instead of default partial'
+     PRINT *,'                 steps.'
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'       Files ', TRIM(cn_fhgr),', ', TRIM(cn_fzgr),', ', TRIM(cn_fmsk)
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file : degraded_cdfvar.nc '
+     PRINT *,'       netcdf file : flsdc.nc'
+     PRINT *,'      '
+    STOP
+  ENDIF
+
+  cglobal = 'Partial step computation'
+  ijarg = 1 ; ii = 0
+  DO WHILE ( ijarg <= narg )
+     CALL getarg(ijarg, cldum ) ; ijarg = ijarg + 1 
+     SELECT CASE (cldum) 
+     CASE ('-full' )
+        lfull = .true. 
+        cglobal = 'full step computation'
+     CASE DEFAULT 
+         ii=ii+1
+        SELECT CASE (ii) 
+        CASE ( 1 ) ; cf_tfil  = cldum 
+        CASE ( 2 ) ; cv_nam = cldum 
+        CASE ( 3 ) ; READ(cldum,*) nri  
+        CASE ( 4 ) ; READ(cldum,*) nrj  
+        CASE ( 5 ) ; READ(cldum,*) iimin
+        CASE ( 6 ) ; READ(cldum,*) ijmin
+        CASE DEFAULT
+          PRINT *, ' ERROR : Too many arguments ...'
+          STOP
+        END SELECT
+     END SELECT
+  END DO
+
+  lchk = chkfile(cn_fhgr)
+  lchk = chkfile(cn_fzgr) .OR. lchk
+  lchk = chkfile(cn_fmsk) .OR. lchk
+  lchk = chkfile(cf_tfil) .OR. lchk
+  IF ( lchk ) STOP ! missing file
+
+  cv_dep = 'none'
+  npiglo = getdim (cf_tfil, cn_x)
+  npjglo = getdim (cf_tfil, cn_y)
+  npk    = getdim (cf_tfil, cn_z, cdtrue=cv_dep, kstatus=ierr)
+
+  IF (ierr /= 0 ) THEN
+     npk   = getdim (cf_tfil, 'z', cdtrue=cv_dep, kstatus=ierr)
+     IF (ierr /= 0 ) THEN
+        npk   = getdim (cf_tfil, 'sigma', cdtrue=cv_dep, kstatus=ierr)
+        IF ( ierr /= 0 ) THEN
+           npk = getdim (cf_tfil, 'nav_lev', cdtrue=cv_dep, kstatus=ierr)
+           IF ( ierr /= 0 ) THEN
+              PRINT *,' assume file with no depth'
+              npk=0
+           ENDIF
+        ENDIF
+     ENDIF
+  ENDIF
+
+  npt    = getdim (cf_tfil, cn_t   )
+  nvpk   = getvdim(cf_tfil, cv_nam )
+
+  IF (npk   == 0 ) THEN ; npk = 1;  ENDIF ! no depth dimension ==> 1 level
+  IF (iimin < 2 )  THEN
+     PRINT *,'iimin value is too low'
+     STOP
+  END IF
+  IF (ijmin  < 2 ) THEN
+     PRINT *,'ijmin value is too low'
+     STOP
+  END IF
+  npiglo = ( (npiglo - iimin ) / nri )*nri
+  npjglo = ( (npjglo - ijmin ) / nrj )*nrj
+  ikx = npiglo / nri
+  iky = npjglo / nrj
+
+  PRINT *,'ikx    : ',ikx
+  PRINT *,'iky    : ',iky
+
+  IF (nvpk == 2 ) npk = 1
+  ! IF (nvpk == 3 ) nvpk = npk
+
+  PRINT *, 'npiglo = ', npiglo
+  PRINT *, 'npjglo = ', npjglo
+  PRINT *, 'npk    = ', npk
+  PRINT *, 'npt    = ', npt
+  PRINT *, 'nvpk   = ', nvpk
+  PRINT *, 'depth dim name is ',TRIM(cv_dep)
+
+  ! Allocate arrays
+  ALLOCATE (zmask(npiglo,npjglo) )
+  ALLOCATE (zv(npiglo,npjglo) )
+  ALLOCATE (e1(npiglo,npjglo), e2(npiglo,npjglo), e3(npiglo,npjglo) )
+  ALLOCATE (gdep (npk), e31d(npk), tim(npt) )
+  ALLOCATE (zdep(npk) )
+
+  cv_e1    = cn_ve1t
+  cv_e2    = cn_ve2t
+  cv_e3    = 'e3t_ps'
+  cv_e31d  = cn_ve3t
+  cv_msk   = 'tmask'
+  cv_dep   = cn_gdept
+ 
+  e1(:,:) = getvar  (cn_fhgr, cv_e1,  1,  npiglo, npjglo, kimin=iimin, kjmin=ijmin)
+  e2(:,:) = getvar  (cn_fhgr, cv_e2,  1,  npiglo, npjglo, kimin=iimin, kjmin=ijmin)
+  IF ( lfull )  e31d(:) = getvare3(cn_fzgr, cv_e31d, npk)
+  zdep(:) = getvare3(cn_fzgr, cv_dep, npk)
+  gdep(:) = zdep(  1  :npk)
+
+  ALLOCATE ( stypvar( 1 ), ipk( 1 ), id_varout( 1 ) )
+  ALLOCATE ( stypvar2( 1 ), id_varout2( 1 ) )
+  ALLOCATE ( rdumlon(ikx,iky), rdumlat(ikx,iky), rdummymean(ikx,iky) ) 
+  ALLOCATE ( nflsdc(ikx,iky) )
+  ALLOCATE ( glamf(npiglo+1,npjglo+1), gphif(npiglo+1,npjglo+1))
+
+  glamf = getvar(cn_fhgr, cn_glamf, 1, npiglo+1 , npjglo+1 , kimin=iimin-1 , kjmin=ijmin-1 )
+  gphif = getvar(cn_fhgr, cn_gphif, 1, npiglo+1 , npjglo+1 , kimin=iimin-1 , kjmin=ijmin-1 )
+
+  DO jj=1,iky
+     DO ji=1,ikx
+        rdumlat(ji,jj) = 0.5 * ( gphif((ji-1)*nri+1,(jj-1)*nrj+1) + gphif( ji   *nri+1,jj*nrj+1) )
+        rdumlon(ji,jj) = 0.5 * ( glamf( ji   *nri+1,(jj-1)*nrj+1) + glamf((ji-1)*nri+1,jj*nrj+1) )
+     END DO
+  END DO
+
+  ipk(:) = npk ! mean for each level
+
+  ierr=getvaratt (cf_tfil, cv_nam, clunits, zspval, cllong_name, clshort_name)
+
+  ! define new variables for output 
+  stypvar%rmissing_value    = 99999.
+  stypvar%scale_factor      = 1.
+  stypvar%add_offset        = 0.
+  stypvar%savelog10         = 0.
+  stypvar%conline_operation = 'N/A'
+
+  stypvar%cunits         = TRIM(clunits)
+  stypvar%valid_min      = -100000.
+  stypvar%valid_max      = 100000.
+  stypvar%cname          = 'degraded_'//TRIM(cv_nam)
+  stypvar%clong_name     = 'degraded '//TRIM(cllong_name)
+  stypvar%cshort_name    = 'degraded_'//TRIM(clshort_name)
+
+  stypvar2%rmissing_value    = 99999.
+  stypvar2%scale_factor      = 1.
+  stypvar2%add_offset        = 0.
+  stypvar2%savelog10         = 0.
+  stypvar2%conline_operation = 'N/A'
+
+  stypvar2%valid_min      = 0.
+  stypvar2%valid_max      = 100000.
+  stypvar2%cname          = 'flsdc'
+  stypvar2%clong_name     = 'fluid sub-domain counter'
+  stypvar2%cshort_name    = 'fdsdc'
+
+  IF ( nvpk == 2 ) THEN
+     stypvar%caxis       = 'TYX'
+     stypvar2%caxis      = 'YX'
+  ELSE
+     stypvar%caxis       = 'TZYX'
+     stypvar2%caxis      = 'ZYX'
+  END IF
+
+  ! create output fileset
+  cf_ncout  = 'degraded_'//TRIM(cv_nam)//'.nc'
+  cf_ncout2 = 'flsdc.nc'
+  ncout  = create      (cf_ncout ,   'none',  ikx,   iky,   npk, cdep=cv_dep)
+  ncout2 = create      (cf_ncout2,   'none',  ikx,   iky,   npk, cdep=cv_dep)
+  ierr  = createvar   (ncout ,      stypvar , 1 , ipk,   id_varout  , cdglobal=TRIM(cglobal) ) 
+  ierr  = createvar   (ncout2,      stypvar2, 1 , ipk,   id_varout2 , cdglobal=TRIM(cglobal) ) 
+  ierr  = putheadervar(ncout ,      cf_tfil,  ikx, iky, npk, pnavlon=rdumlon, pnavlat=rdumlat, pdep=gdep, cdep=cv_dep)
+  ierr  = putheadervar(ncout2,      cn_fmsk,  ikx, iky, npk, pnavlon=rdumlon, pnavlat=rdumlat, pdep=gdep, cdep=cv_dep)
+  tim   = getvar1d(cf_tfil, cn_vtimec, npt)
+  ierr  = putvar1d(ncout,  tim,       npt, 'T')
+
+  DO jk = 1, npk
+     ik = jk
+     ! Get variable v at ik
+     zmask(:,:) = getvar(cn_fmsk, cv_msk, ik, npiglo, npjglo, kimin=iimin, kjmin=ijmin          )
+     IF ( lfull ) THEN
+        e3(:,:) = e31d(jk)
+     ELSE
+        e3(:,:) = getvar(cn_fzgr, cv_e3,    ik, npiglo, npjglo, kimin=iimin, kjmin=ijmin, ldiom=.TRUE.)
+     END IF
+     DO jt=1,npt
+        ! 
+        zv   (:,:) = getvar(cf_tfil,  cv_nam,   ik, npiglo, npjglo, kimin=iimin, kjmin=ijmin, ktime=jt)
+        DO jj=1,iky
+           DO ji=1,ikx
+              dvol = 0.d0
+              dsum = 0.d0
+              msks = 0
+              DO jrj=1,nrj
+                 DO jri=1,nri
+                    ix = (ji-1)*nri+jri
+                    iy = (jj-1)*nrj+jrj
+                    dvol2d = e1(ix,iy) * e2(ix,iy) * e3(ix,iy) * zmask(ix,iy)
+                    msks = msks + zmask(ix,iy)
+                    dvol = dvol + dvol2d
+                    dsum = dsum + zv(ix,iy) * dvol2d
+                 END DO
+              END DO
+              IF ( dvol > 0.d0 ) THEN
+                 rdummymean(ji,jj) = dsum/dvol
+              ELSE
+                 rdummymean(ji,jj) = 99999.
+              END IF
+              nflsdc(ji,jj) = msks
+           END DO
+        END DO
+        ierr = putvar(ncout , id_varout(1), rdummymean , jk, ikx, iky, ktime=jt )
+     END DO ! time loop
+     ierr = putvar(ncout2, id_varout2(1), DBLE(nflsdc), jk, ikx, iky )
+  END DO  
+
+  ierr = closeout(ncout )
+  ierr = closeout(ncout2)
+
+9004 FORMAT(f9.2,' ',i2,' ',f9.2)
+
+END PROGRAM cdfdegradt
diff --git a/src/cdfdegradu.f90 b/src/cdfdegradu.f90
new file mode 100644
index 0000000..12d7e7c
--- /dev/null
+++ b/src/cdfdegradu.f90
@@ -0,0 +1,316 @@
+PROGRAM cdfdegradu
+  !!======================================================================
+  !!                   ***  PROGRAM  cdfdegradu  ***
+  !!=====================================================================
+  !!  ** Purpose : Degrade horizontal resolution of NEMO gridU output
+  !!
+  !!  ** Method  : Degradation procedure ensuring the conservation
+  !!               of water fluxes.
+  !!
+  !! History : 1.0 : 11/2011  : X. Meunier : Original code
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id$
+  !! Copyright (c) 2011, 
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: nflsdc           ! array for fluid sub-domain counter
+  INTEGER(KIND=4), DIMENSION(:),     ALLOCATABLE :: ipk, id_varout, id_varout2
+  INTEGER(KIND=4)                           :: ji, jj, jk, jt, jri, jrj   ! dummy loop index
+  INTEGER(KIND=4)                           :: ik, ii, ij         !
+  INTEGER(KIND=4)                           :: ix, iy             !
+  INTEGER(KIND=4)                           :: ierr               ! error status
+  INTEGER(KIND=4)                           :: nri=1, nrj=1       ! scale degrading factor along i and j  
+  INTEGER(KIND=4)                           :: iimin=1            ! indice from where the filtering begins
+  INTEGER(KIND=4)                           :: ijmin=2            ! indice from where the filtering begins
+  INTEGER(KIND=4)                           :: narg, iargc, ijarg ! browse command line
+  INTEGER(KIND=4)                           :: npiglo, npjglo     ! size of the domain
+  INTEGER(KIND=4)                           :: npk, npt           ! size of the domain
+  INTEGER(KIND=4)                           :: ncout, ncout2      ! ncid of output file
+  INTEGER(KIND=4)                           :: msks               ! mask sum on each coarse cells
+  INTEGER(KIND=4)                           :: nvpk               ! vertical levels in working variable
+  INTEGER(KIND=4)                           :: ikx=1, iky=1       ! dims of netcdf output file
+
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zmask              ! 2D mask at current level
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: glamf, gphif       ! lon, lat
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e1, e3, zv         ! metrics, variable
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: rdumlon, rdumlat   ! dummy lon/lat for output file
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: rdummymean         ! array for mean value on output file
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim                ! time counter
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: gdep               ! depth 
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: zdep               ! depth of the whole vertical levels
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: e31d               ! 1d vertical spacing
+  REAL(KIND=4)                              :: zspval             ! missing value
+
+  REAL(KIND=8)                              :: dvol, dsum, dsurf  ! cumulated values
+  REAL(KIND=8)                              :: dvol2d, dsum2d     !
+
+  CHARACTER(LEN=256)                        :: cf_ufil            ! input filename
+  CHARACTER(LEN=256)                        :: cf_ncout,cf_ncout2 ! output file name
+  !
+  CHARACTER(LEN=256)                        :: cv_nam             ! current variable name
+  CHARACTER(LEN=256)                        :: cv_dep             ! deptht name
+  CHARACTER(LEN=20)                         :: cv_e1              ! horizontal metrics names
+  CHARACTER(LEN=20)                         :: cv_e3, cv_e31d     ! vertical metrics names
+  CHARACTER(LEN=20)                         :: cv_msk             ! mask variable name
+  !
+  CHARACTER(LEN=256)                        :: clunits            ! attribute of output file : units
+  CHARACTER(LEN=256)                        :: cldum              ! dummy char variable
+  CHARACTER(LEN=256)                        :: cllong_name        !     "      long name
+  CHARACTER(LEN=256)                        :: cglobal            !     "      global 
+  CHARACTER(LEN=256)                        :: clshort_name       !     "      short name
+  !
+  TYPE(variable), DIMENSION(:), ALLOCATABLE :: stypvar            ! structure of output
+  TYPE(variable), DIMENSION(:), ALLOCATABLE :: stypvar2           ! structure of sub-domain counter output
+
+  LOGICAL                                   :: lfull     = .false.! full step  flag
+  LOGICAL                                   :: lchk               ! flag for missing files
+ 
+ !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  narg = iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage : cdfdegradu IN-Ufile IN-var ri rj [i0 j0]'
+     PRINT *,'       ... [-full]'
+     PRINT *,'       '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'       Degrad the horizontal resolution of NEMO U-grid ouput,       ' 
+     PRINT *,'       for each z-level and time step, with a ratio of ri along     '
+     PRINT *,'       x direction and rj along y direction. If specified, the input'
+     PRINT *,'       grid is considered starting from the indices i0 and j0.      ' 
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       IN-Ufile  : netcdf U-file.' 
+     PRINT *,'       IN-var    : name of netcdf variable to work with' 
+     PRINT *,'       ri        : degradation ratio for x-direction   ' 
+     PRINT *,'       rj        : degradation ratio for y-direction   ' 
+     PRINT *,'      '
+     PRINT *,'     OPTIONS : '
+     PRINT *,'       [i0 j0] : spatial indices from where starting the procedure   '
+     PRINT *,'                 of degradation.                                    ' 
+     PRINT *,'       [-full] : flag for full steps grid, instead of default partial'
+     PRINT *,'                 steps.'
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'       Files ', TRIM(cn_fhgr),', ', TRIM(cn_fzgr),', ', TRIM(cn_fmsk)
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file : degraded_cdfvar.nc '
+     PRINT *,'       netcdf file : flsdc.nc'
+     PRINT *,'      '
+    STOP
+  ENDIF
+
+  cglobal = 'Partial step computation'
+  ijarg = 1 ; ii = 0
+  DO WHILE ( ijarg <= narg )
+     CALL getarg(ijarg, cldum ) ; ijarg = ijarg + 1 
+     SELECT CASE (cldum) 
+     CASE ('-full' )
+        lfull = .true. 
+        cglobal = 'full step computation'
+     CASE DEFAULT 
+         ii=ii+1
+        SELECT CASE (ii) 
+        CASE ( 1 ) ; cf_ufil  = cldum 
+        CASE ( 2 ) ; cv_nam = cldum 
+        CASE ( 3 ) ; READ(cldum,*) nri  
+        CASE ( 4 ) ; READ(cldum,*) nrj  
+        CASE ( 5 ) ; READ(cldum,*) iimin
+        CASE ( 6 ) ; READ(cldum,*) ijmin
+        CASE DEFAULT
+          PRINT *, ' ERROR : Too many arguments ...'
+          STOP
+        END SELECT
+     END SELECT
+  END DO
+
+  lchk = chkfile(cn_fhgr)
+  lchk = chkfile(cn_fzgr) .OR. lchk
+  lchk = chkfile(cn_fmsk) .OR. lchk
+  lchk = chkfile(cf_ufil) .OR. lchk
+  IF ( lchk ) STOP ! missing file
+
+  cv_dep = 'none'
+  npiglo = getdim (cf_ufil, cn_x)
+  npjglo = getdim (cf_ufil, cn_y)
+  npk    = getdim (cf_ufil, cn_z, cdtrue=cv_dep, kstatus=ierr)
+
+  IF (ierr /= 0 ) THEN
+     npk   = getdim (cf_ufil, 'z', cdtrue=cv_dep, kstatus=ierr)
+     IF (ierr /= 0 ) THEN
+        npk   = getdim (cf_ufil, 'sigma', cdtrue=cv_dep, kstatus=ierr)
+        IF ( ierr /= 0 ) THEN
+           npk = getdim (cf_ufil, 'nav_lev', cdtrue=cv_dep, kstatus=ierr)
+           IF ( ierr /= 0 ) THEN
+              PRINT *,' assume file with no depth'
+              npk=0
+           ENDIF
+        ENDIF
+     ENDIF
+  ENDIF
+
+  npt    = getdim (cf_ufil, cn_t)
+  nvpk   = getvdim(cf_ufil, cv_nam)
+
+  IF (npk   == 0 ) THEN ; npk = 1;  ENDIF ! no depth dimension ==> 1 level
+  IF (iimin < 1 )  THEN
+     PRINT *,'iimin value is too low'
+     STOP
+  END IF
+  IF (ijmin  < 2 ) THEN
+     PRINT *,'ijmin value is too low'
+     STOP
+  END IF
+  npiglo = ( (npiglo - iimin - 1 ) / nri )*nri + 1
+  npjglo = ( (npjglo - ijmin ) / nrj )*nrj
+  ikx = ( npiglo - 1 ) / nri + 1
+  iky = npjglo / nrj
+
+  PRINT *,'ikx    : ',ikx
+  PRINT *,'iky    : ',iky
+
+  IF (nvpk == 2 ) npk = 1
+  ! IF (nvpk == 3 ) nvpk = npk
+
+  PRINT *, 'npiglo = ', npiglo
+  PRINT *, 'npjglo = ', npjglo
+  PRINT *, 'npk    = ', npk
+  PRINT *, 'npt    = ', npt
+  PRINT *, 'nvpk   = ', nvpk
+  PRINT *, 'depth dim name is ',TRIM(cv_dep)
+
+  ! Allocate arrays
+  ALLOCATE (zmask(npiglo,npjglo) )
+  ALLOCATE (zv(npiglo,npjglo) )
+  ALLOCATE (e1(npiglo,npjglo), e3(npiglo,npjglo) )
+  ALLOCATE (gdep (npk), e31d(npk), tim(npt) )
+  ALLOCATE (zdep(npk) )
+
+  cv_e1    = cn_ve1u
+  cv_e3    = 'e3t_ps'
+  cv_e31d  = cn_ve3t
+  cv_msk = 'umask'
+  cv_dep   = cn_gdept
+ 
+  e1(:,:) = getvar  (cn_fhgr, cv_e1,  1,  npiglo, npjglo, kimin=iimin, kjmin=ijmin)
+  IF ( lfull )  e31d(:) = getvare3(cn_fzgr, cv_e31d, npk)
+  zdep(:) = getvare3(cn_fzgr, cv_dep, npk)
+  gdep(:) = zdep(  1  :npk)
+
+  ALLOCATE ( stypvar( 1 ), ipk( 1 ), id_varout( 1 ) )
+  ALLOCATE ( stypvar2( 1 ), id_varout2( 1 ) )
+  ALLOCATE ( rdumlon(ikx,iky), rdumlat(ikx,iky), rdummymean(ikx,iky) ) 
+  ALLOCATE ( nflsdc(ikx,iky) )
+  ALLOCATE ( glamf(npiglo,npjglo+1), gphif(npiglo,npjglo+1))
+
+  glamf = getvar(cn_fhgr, cn_glamf, 1, npiglo , npjglo+1 , kimin=iimin , kjmin=ijmin-1 )
+  gphif = getvar(cn_fhgr, cn_gphif, 1, npiglo , npjglo+1 , kimin=iimin , kjmin=ijmin-1 )
+
+  DO ji=1,ikx
+     DO jj=1,iky
+        rdumlat(ji,jj) = 0.5 * ( gphif((ji-1)*nri+1,(jj-1)*nrj+1) + gphif((ji-1)*nri+1,jj*nrj+1) )
+        rdumlon(ji,jj) = 0.5 * ( glamf((ji-1)*nri+1,(jj-1)*nrj+1) + glamf((ji-1)*nri+1,jj*nrj+1) )
+     END DO
+  END DO
+
+  ipk(:) = npk ! mean for each level
+
+  ierr=getvaratt (cf_ufil, cv_nam, clunits, zspval, cllong_name, clshort_name)
+
+  ! define new variables for output 
+  stypvar%rmissing_value    = 99999.
+  stypvar%scale_factor      = 1.
+  stypvar%add_offset        = 0.
+  stypvar%savelog10         = 0.
+  stypvar%conline_operation = 'N/A'
+
+  stypvar%cunits         = TRIM(clunits)
+  stypvar%valid_min      = -100000.
+  stypvar%valid_max      = 100000.
+  stypvar%cname          = 'degraded_'//TRIM(cv_nam)
+  stypvar%clong_name     = 'degraded '//TRIM(cllong_name)
+  stypvar%cshort_name    = 'degraded_'//TRIM(clshort_name)
+
+  stypvar2%rmissing_value    = 99999.
+  stypvar2%scale_factor      = 1.
+  stypvar2%add_offset        = 0.
+  stypvar2%savelog10         = 0.
+  stypvar2%conline_operation = 'N/A'
+
+  stypvar2%valid_min      = 0.
+  stypvar2%valid_max      = 100000.
+  stypvar2%cname          = 'flsdc'
+  stypvar2%clong_name     = 'fluid sub-domain counter'
+  stypvar2%cshort_name    = 'fdsdc'
+
+  IF ( nvpk == 2 ) THEN
+     stypvar%caxis       = 'TYX'
+     stypvar2%caxis      = 'YX'
+  ELSE
+     stypvar%caxis       = 'TZYX'
+     stypvar2%caxis      = 'ZYX'
+  END IF
+
+  ! create output fileset
+  cf_ncout  = 'degraded_'//TRIM(cv_nam)//'.nc'
+  cf_ncout2 = 'flsdc.nc'
+  ncout  = create      (cf_ncout ,   'none',  ikx,   iky,   npk, cdep=cv_dep)
+  ncout2 = create      (cf_ncout2,   'none',  ikx,   iky,   npk, cdep=cv_dep)
+  ierr  = createvar   (ncout ,      stypvar , 1 , ipk,   id_varout  , cdglobal=TRIM(cglobal) ) 
+  ierr  = createvar   (ncout2,      stypvar2, 1 , ipk,   id_varout2 , cdglobal=TRIM(cglobal) ) 
+  ierr  = putheadervar(ncout ,      cf_ufil,  ikx, iky, npk, pnavlon=rdumlon, pnavlat=rdumlat, pdep=gdep, cdep=cv_dep)
+  ierr  = putheadervar(ncout2,      cn_fmsk,  ikx, iky, npk, pnavlon=rdumlon, pnavlat=rdumlat, pdep=gdep, cdep=cv_dep)
+  tim   = getvar1d(cf_ufil, cn_vtimec, npt)
+  ierr  = putvar1d(ncout,  tim,       npt, 'T')
+
+  DO jk = 1, npk
+     ik = jk
+     ! Get variable v at ik
+     zmask(:,:) = getvar(cn_fmsk, cv_msk, ik, npiglo, npjglo, kimin=iimin, kjmin=ijmin          )
+     IF ( lfull ) THEN
+        e3(:,:) = e31d(jk)
+     ELSE
+        e3(:,:) = getvar(cn_fzgr, cv_e3,    ik, npiglo, npjglo, kimin=iimin, kjmin=ijmin, ldiom=.TRUE.)
+     END IF
+     DO jt=1,npt
+        ! 
+        zv   (:,:) = getvar(cf_ufil,  cv_nam,   ik, npiglo, npjglo, kimin=iimin, kjmin=ijmin, ktime=jt)
+        DO ji=1,ikx
+           ix = (ji-1)*nri+1
+           DO jj=1,iky
+              dvol = 0.d0
+              dsum = 0.d0
+              msks = 0
+              DO jrj=1,nrj
+                 iy = (jj-1)*nrj+jrj
+                 dvol2d = e1(ix,iy) * e3(ix,iy) * zmask(ix,iy)
+                 msks = msks + zmask(ix,iy)
+                 dvol = dvol + dvol2d
+                 dsum = dsum + zv(ix,iy) * dvol2d
+              END DO
+              IF ( dvol > 0.d0 ) THEN
+                 rdummymean(ji,jj) = dsum/dvol
+              ELSE
+                 rdummymean(ji,jj) = 99999.
+              END IF
+              nflsdc(ji,jj) = msks
+           END DO
+        END DO
+        ierr = putvar(ncout , id_varout(1), rdummymean , jk, ikx, iky, ktime=jt )
+     END DO ! time loop
+     ierr = putvar(ncout2, id_varout2(1), DBLE(nflsdc), jk, ikx, iky )
+  END DO  
+
+  ierr = closeout(ncout )
+  ierr = closeout(ncout2)
+
+9004 FORMAT(f9.2,' ',i2,' ',f9.2)
+
+END PROGRAM cdfdegradu
diff --git a/src/cdfdegradv.f90 b/src/cdfdegradv.f90
new file mode 100644
index 0000000..eacd9a2
--- /dev/null
+++ b/src/cdfdegradv.f90
@@ -0,0 +1,315 @@
+PROGRAM cdfdegradv
+  !!======================================================================
+  !!                   ***  PROGRAM  cdfdegradv  ***
+  !!=====================================================================
+  !!  ** Purpose : Degrade horizontal resolution of NEMO gridV output
+  !!
+  !!  ** Method  : Degradation procedure ensuring the conservation
+  !!               of water fluxes.
+  !!
+  !! History : 1.0 : 11/2011  : X. Meunier : Original code
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id$
+  !! Copyright (c) 2011, 
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4), DIMENSION(:,:), ALLOCATABLE :: nflsdc           ! array for fluid sub-domain counter
+  INTEGER(KIND=4), DIMENSION(:),   ALLOCATABLE :: ipk, id_varout, id_varout2
+  INTEGER(KIND=4)                           :: ji, jj, jk, jt, jri, jrj   ! dummy loop index
+  INTEGER(KIND=4)                           :: ik, ii, ij         !
+  INTEGER(KIND=4)                           :: ix, iy             !
+  INTEGER(KIND=4)                           :: ierr               ! error status
+  INTEGER(KIND=4)                           :: nri=1, nrj=1       ! scale degrading factor along i and j  
+  INTEGER(KIND=4)                           :: iimin=2            ! indice from where the filtering begins
+  INTEGER(KIND=4)                           :: ijmin=1            ! indice from where the filtering begins
+  INTEGER(KIND=4)                           :: narg, iargc, ijarg ! browse command line
+  INTEGER(KIND=4)                           :: npiglo, npjglo     ! size of the domain
+  INTEGER(KIND=4)                           :: npk, npt           ! size of the domain
+  INTEGER(KIND=4)                           :: ncout, ncout2      ! ncid of output file
+  INTEGER(KIND=4)                           :: msks               ! mask sum on each coarse cells
+  INTEGER(KIND=4)                           :: nvpk               ! vertical levels in working variable
+  INTEGER(KIND=4)                           :: ikx=1, iky=1       ! dims of netcdf output file
+
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zmask              ! 2D mask at current level
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: glamf, gphif       ! lon, lat
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e2, e3, zv         ! metrics, variable
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: rdumlon, rdumlat   ! dummy lon/lat for output file
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: rdummymean         ! array for mean value on output file
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: gdep               ! depth 
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: zdep               ! depth of the whole vertical levels
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: e31d               ! 1d vertical spacing
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim                ! time counter
+  REAL(KIND=4)                              :: zspval             ! missing value
+
+  REAL(KIND=8)                              :: dvol, dsum, dsurf  ! cumulated values
+  REAL(KIND=8)                              :: dvol2d, dsum2d     !
+
+  CHARACTER(LEN=256)                        :: cf_vfil            ! input filename
+  CHARACTER(LEN=256)                        :: cf_ncout,cf_ncout2 ! output file name
+  !
+  CHARACTER(LEN=256)                        :: cv_nam             ! current variable name
+  CHARACTER(LEN=256)                        :: cv_dep             ! deptht name
+  CHARACTER(LEN=20)                         :: cv_e2              ! horizontal metrics names
+  CHARACTER(LEN=20)                         :: cv_e3, cv_e31d     ! vertical metrics names
+  CHARACTER(LEN=20)                         :: cv_msk             ! mask variable name
+  !
+  CHARACTER(LEN=256)                        :: clunits            ! attribute of output file : units
+  CHARACTER(LEN=256)                        :: cllong_name        !     "      long name
+  CHARACTER(LEN=256)                        :: cglobal            !     "      global 
+  CHARACTER(LEN=256)                        :: clshort_name       !     "      short name
+  CHARACTER(LEN=256)                        :: cldum              ! dummy char variable
+
+  TYPE(variable), DIMENSION(:), ALLOCATABLE :: stypvar            ! structure of output
+  TYPE(variable), DIMENSION(:), ALLOCATABLE :: stypvar2           ! structure of sub-domain counter output
+
+  LOGICAL                                   :: lfull     = .false.! full step  flag
+  LOGICAL                                   :: lchk               ! flag for missing files
+ 
+ !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  narg = iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage : cdfdegradv IN-Vfile IN-var ri rj [i0 j0]'
+     PRINT *,'       ... [-full]'
+     PRINT *,'       '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'       Degrad the horizontal resolution of NEMO V-grid ouput,       ' 
+     PRINT *,'       for each z-level and time step, with a ratio of ri along     '
+     PRINT *,'       x direction and rj along y direction. If specified, the input'
+     PRINT *,'       grid is considered starting from the indices i0 and j0.      ' 
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       IN-Vfile  : netcdf V-file.' 
+     PRINT *,'       IN-var    : name of netcdf variable to work with' 
+     PRINT *,'       ri        : degradation ratio for x-direction   ' 
+     PRINT *,'       rj        : degradation ratio for y-direction   ' 
+     PRINT *,'      '
+     PRINT *,'     OPTIONS : '
+     PRINT *,'       [i0 j0] : spatial indices from where starting the procedure   '
+     PRINT *,'                 of degradation.                                    ' 
+     PRINT *,'       [-full] : flag for full steps grid, instead of default partial'
+     PRINT *,'                 steps.'
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'       Files ', TRIM(cn_fhgr),', ', TRIM(cn_fzgr),', ', TRIM(cn_fmsk)
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file : degraded_cdfvar.nc '
+     PRINT *,'       netcdf file : flsdc.nc'
+     PRINT *,'      '
+    STOP
+  ENDIF
+
+  cglobal = 'Partial step computation'
+  ijarg = 1 ; ii = 0
+  DO WHILE ( ijarg <= narg )
+     CALL getarg(ijarg, cldum ) ; ijarg = ijarg + 1 
+     SELECT CASE (cldum) 
+     CASE ('-full' )
+        lfull = .true. 
+        cglobal = 'full step computation'
+     CASE DEFAULT 
+         ii=ii+1
+        SELECT CASE (ii) 
+        CASE ( 1 ) ; cf_vfil  = cldum 
+        CASE ( 2 ) ; cv_nam = cldum 
+        CASE ( 3 ) ; READ(cldum,*) nri  
+        CASE ( 4 ) ; READ(cldum,*) nrj  
+        CASE ( 5 ) ; READ(cldum,*) iimin
+        CASE ( 6 ) ; READ(cldum,*) ijmin
+        CASE DEFAULT
+          PRINT *, ' ERROR : Too many arguments ...'
+          STOP
+        END SELECT
+     END SELECT
+  END DO
+
+  lchk = chkfile(cn_fhgr)
+  lchk = chkfile(cn_fzgr) .OR. lchk
+  lchk = chkfile(cn_fmsk) .OR. lchk
+  lchk = chkfile(cf_vfil) .OR. lchk
+  IF ( lchk ) STOP ! missing file
+
+  cv_dep = 'none'
+  npiglo = getdim (cf_vfil, cn_x)
+  npjglo = getdim (cf_vfil, cn_y)
+  npk    = getdim (cf_vfil, cn_z, cdtrue=cv_dep, kstatus=ierr)
+
+  IF (ierr /= 0 ) THEN
+     npk   = getdim (cf_vfil, 'z', cdtrue=cv_dep, kstatus=ierr)
+     IF (ierr /= 0 ) THEN
+        npk   = getdim (cf_vfil, 'sigma', cdtrue=cv_dep, kstatus=ierr)
+        IF ( ierr /= 0 ) THEN
+           npk = getdim (cf_vfil, 'nav_lev', cdtrue=cv_dep, kstatus=ierr)
+           IF ( ierr /= 0 ) THEN
+              PRINT *,' assume file with no depth'
+              npk=0
+           ENDIF
+        ENDIF
+     ENDIF
+  ENDIF
+
+  npt    = getdim (cf_vfil, cn_t)
+  nvpk   = getvdim(cf_vfil, cv_nam)
+
+  IF (npk   == 0 ) THEN ; npk = 1;  ENDIF ! no depth dimension ==> 1 level
+  IF (iimin < 2 )  THEN
+     PRINT *,'iimin value is too low'
+     STOP
+  END IF
+  IF (ijmin  < 1 ) THEN
+     PRINT *,'ijmin value is too low'
+     STOP
+  END IF
+  npiglo = ( (npiglo - iimin ) / nri )*nri
+  npjglo = ( (npjglo - ijmin - 1 ) / nrj )*nrj + 1
+  ikx = npiglo / nri
+  iky = ( npjglo - 1 ) / nrj + 1
+
+  PRINT *,'ikx    : ',ikx
+  PRINT *,'iky    : ',iky
+
+  IF (nvpk == 2 ) npk = 1
+  ! IF (nvpk == 3 ) nvpk = npk
+
+  PRINT *, 'npiglo = ', npiglo
+  PRINT *, 'npjglo = ', npjglo
+  PRINT *, 'npk    = ', npk
+  PRINT *, 'npt    = ', npt
+  PRINT *, 'nvpk   = ', nvpk
+  PRINT *, 'depth dim name is ',TRIM(cv_dep)
+
+  ! Allocate arrays
+  ALLOCATE (zmask(npiglo,npjglo) )
+  ALLOCATE (zv(npiglo,npjglo) )
+  ALLOCATE (e2(npiglo,npjglo), e3(npiglo,npjglo) )
+  ALLOCATE (gdep (npk), e31d(npk), tim(npt) )
+  ALLOCATE (zdep(npk) )
+
+  cv_e2    = cn_ve2v
+  cv_e3    = 'e3t_ps'
+  cv_e31d  = cn_ve3t
+  cv_msk = 'vmask'
+  cv_dep   = cn_gdept
+ 
+  e2(:,:) = getvar  (cn_fhgr, cv_e2,  1,  npiglo, npjglo, kimin=iimin, kjmin=ijmin)
+  IF ( lfull )  e31d(:) = getvare3(cn_fzgr, cv_e31d, npk)
+  zdep(:) = getvare3(cn_fzgr, cv_dep, npk)
+  gdep(:) = zdep(  1  :npk)
+
+  ALLOCATE ( stypvar( 1 ), ipk( 1 ), id_varout( 1 ) )
+  ALLOCATE ( stypvar2( 1 ), id_varout2( 1 ) )
+  ALLOCATE ( rdumlon(ikx,iky), rdumlat(ikx,iky), rdummymean(ikx,iky) ) 
+  ALLOCATE ( nflsdc(ikx,iky) )
+  ALLOCATE ( glamf(npiglo+1,npjglo), gphif(npiglo+1,npjglo))
+
+  glamf = getvar(cn_fhgr, cn_glamf, 1, npiglo+1 , npjglo , kimin=iimin-1 , kjmin=ijmin )
+  gphif = getvar(cn_fhgr, cn_gphif, 1, npiglo+1 , npjglo , kimin=iimin-1 , kjmin=ijmin )
+  DO jj=1,iky
+     DO ji=1,ikx
+        rdumlat(ji,jj) = 0.5 * ( gphif((ji-1)*nri+1,(jj-1)*nrj+1) + gphif(ji*nri+1,(jj-1)*nrj+1) )
+        rdumlon(ji,jj) = 0.5 * ( glamf((ji-1)*nri+1,(jj-1)*nrj+1) + glamf(ji*nri+1,(jj-1)*nrj+1) )
+     END DO
+  END DO
+
+  ipk(:) = npk ! mean for each level
+
+  ierr=getvaratt (cf_vfil, cv_nam, clunits, zspval, cllong_name, clshort_name)
+
+  ! define new variables for output 
+  stypvar%rmissing_value    = 99999.
+  stypvar%scale_factor      = 1.
+  stypvar%add_offset        = 0.
+  stypvar%savelog10         = 0.
+  stypvar%conline_operation = 'N/A'
+
+  stypvar%cunits         = TRIM(clunits)
+  stypvar%valid_min      = -100000.
+  stypvar%valid_max      = 100000.
+  stypvar%cname          = 'degraded_'//TRIM(cv_nam)
+  stypvar%clong_name     = 'degraded '//TRIM(cllong_name)
+  stypvar%cshort_name    = 'degraded_'//TRIM(clshort_name)
+
+  stypvar2%rmissing_value    = 99999.
+  stypvar2%scale_factor      = 1.
+  stypvar2%add_offset        = 0.
+  stypvar2%savelog10         = 0.
+  stypvar2%conline_operation = 'N/A'
+
+  stypvar2%valid_min      = 0.
+  stypvar2%valid_max      = 100000.
+  stypvar2%cname          = 'flsdc'
+  stypvar2%clong_name     = 'fluid sub-domain counter'
+  stypvar2%cshort_name    = 'fdsdc'
+
+  IF ( nvpk == 2 ) THEN
+     stypvar%caxis       = 'TYX'
+     stypvar2%caxis      = 'YX'
+  ELSE
+     stypvar%caxis       = 'TZYX'
+     stypvar2%caxis      = 'ZYX'
+  END IF
+
+  ! create output fileset
+  cf_ncout  = 'degraded_'//TRIM(cv_nam)//'.nc'
+  cf_ncout2 = 'flsdc.nc'
+  ncout  = create      (cf_ncout ,   'none',  ikx,   iky,   npk, cdep=cv_dep)
+  ncout2 = create      (cf_ncout2,   'none',  ikx,   iky,   npk, cdep=cv_dep)
+  ierr  = createvar   (ncout ,      stypvar , 1 , ipk,   id_varout  , cdglobal=TRIM(cglobal) ) 
+  ierr  = createvar   (ncout2,      stypvar2, 1 , ipk,   id_varout2 , cdglobal=TRIM(cglobal) ) 
+  ierr  = putheadervar(ncout ,      cf_vfil,  ikx, iky, npk, pnavlon=rdumlon, pnavlat=rdumlat, pdep=gdep, cdep=cv_dep)
+  ierr  = putheadervar(ncout2,      cn_fmsk,  ikx, iky, npk, pnavlon=rdumlon, pnavlat=rdumlat, pdep=gdep, cdep=cv_dep)
+  tim   = getvar1d(cf_vfil, cn_vtimec, npt)
+  ierr  = putvar1d(ncout,  tim,       npt, 'T')
+
+  DO jk = 1, npk
+     ik = jk
+     ! Get variable v at ik
+     zmask(:,:) = getvar(cn_fmsk, cv_msk, ik, npiglo, npjglo, kimin=iimin, kjmin=ijmin          )
+     IF ( lfull ) THEN
+        e3(:,:) = e31d(jk)
+     ELSE
+        e3(:,:) = getvar(cn_fzgr, cv_e3,    ik, npiglo, npjglo, kimin=iimin, kjmin=ijmin, ldiom=.TRUE.)
+     END IF
+     DO jt=1,npt
+        ! 
+        zv   (:,:) = getvar(cf_vfil,  cv_nam,   ik, npiglo, npjglo, kimin=iimin, kjmin=ijmin, ktime=jt)
+        DO jj=1,iky
+           iy = (jj-1)*nrj+1
+           DO ji=1,ikx
+              dvol = 0.d0
+              dsum = 0.d0
+              msks = 0
+              DO jri=1,nri
+                 ix = (ji-1)*nri+jri
+                 dvol2d = e2(ix,iy) * e3(ix,iy) * zmask(ix,iy)
+                 msks = msks + zmask(ix,iy)
+                 dvol = dvol + dvol2d
+                 dsum = dsum + zv(ix,iy) * dvol2d
+              END DO
+              IF ( dvol > 0.d0 ) THEN
+                 rdummymean(ji,jj) = dsum/dvol
+              ELSE
+                 rdummymean(ji,jj) = 99999.
+              END IF
+              nflsdc(ji,jj) = msks
+           END DO
+        END DO
+        ierr = putvar(ncout , id_varout(1), rdummymean , jk, ikx, iky, ktime=jt )
+     END DO ! time loop
+     ierr = putvar(ncout2, id_varout2(1), DBLE(nflsdc), jk, ikx, iky )
+  END DO  
+
+  ierr = closeout(ncout )
+  ierr = closeout(ncout2)
+
+9004 FORMAT(f9.2,' ',i2,' ',f9.2)
+
+END PROGRAM cdfdegradv
diff --git a/src/cdfdegradw.f90 b/src/cdfdegradw.f90
new file mode 100644
index 0000000..58f6203
--- /dev/null
+++ b/src/cdfdegradw.f90
@@ -0,0 +1,314 @@
+PROGRAM cdfdegradw
+  !!======================================================================
+  !!                   ***  PROGRAM  cdfdegradw  ***
+  !!=====================================================================
+  !!  ** Purpose : Degrade horizontal resolution of NEMO gridW output
+  !!
+  !!  ** Method  : Degradation procedure ensuring the conservation
+  !!               of water fluxes.
+  !!
+  !! History : 1.0 : 11/2011  : X. Meunier : Original code
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id$
+  !! Copyright (c) 2011, 
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: nflsdc           ! array for fluid sub-domain counter
+  INTEGER(KIND=4), DIMENSION(:),     ALLOCATABLE :: ipk, id_varout, id_varout2
+  INTEGER(KIND=4)                           :: ji, jj, jk, jt, jri, jrj   ! dummy loop index
+  INTEGER(KIND=4)                           :: ik, ii, ij         !
+  INTEGER(KIND=4)                           :: ix, iy             !
+  INTEGER(KIND=4)                           :: ierr               ! error status
+  INTEGER(KIND=4)                           :: nri=1, nrj=1       ! scale degrading factor along i and j  
+  INTEGER(KIND=4)                           :: iimin=2            ! indice from where the filtering begins
+  INTEGER(KIND=4)                           :: ijmin=2            ! indice from where the filtering begins
+  INTEGER(KIND=4)                           :: narg, iargc, ijarg ! browse command line
+  INTEGER(KIND=4)                           :: npiglo, npjglo     ! size of the domain
+  INTEGER(KIND=4)                           :: npk, npt           ! size of the domain
+  INTEGER(KIND=4)                           :: ncout, ncout2      ! ncid of output file
+  INTEGER(KIND=4)                           :: msks               ! mask sum on each coarse cells
+  INTEGER(KIND=4)                           :: nvpk               ! vertical levels in working variable
+  INTEGER(KIND=4)                           :: ikx=1, iky=1       ! dims of netcdf output file
+
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: glamf, gphif       ! lon, lat
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e1, e2, zv         ! metrics, variable
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: rdumlon, rdumlat   ! dummy lon/lat for output file
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: rdummymean         ! array for mean value on output file
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zmask              ! 2D mask at current level
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim                ! time counter
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: gdep               ! depth 
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: zdep               ! depth of the whole vertical levels
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: e31d               ! 1d vertical spacing
+  REAL(KIND=4)                              :: zspval             ! missing value
+
+  REAL(KIND=8)                              :: dvol, dsum, dsurf  ! cumulated values
+  REAL(KIND=8)                              :: dvol2d, dsum2d     !
+
+  CHARACTER(LEN=256)                        :: cf_wfil            ! input filename
+  CHARACTER(LEN=256)                        :: cf_ncout,cf_ncout2 ! output file name
+  !
+  CHARACTER(LEN=256)                        :: cv_nam             ! current variable name
+  CHARACTER(LEN=256)                        :: cv_dep             ! deptht name
+  CHARACTER(LEN=20)                         :: cv_e1, cv_e2       ! horizontal metrics names
+  CHARACTER(LEN=20)                         :: cv_e3, cv_e31d     ! vertical metrics names
+  CHARACTER(LEN=20)                         :: cv_msk             ! mask variable name
+  !
+  CHARACTER(LEN=256)                        :: clunits            ! attribute of output file : units
+  CHARACTER(LEN=256)                        :: cllong_name        !     "      long name
+  CHARACTER(LEN=256)                        :: cglobal            !     "      global 
+  CHARACTER(LEN=256)                        :: clshort_name       !     "      short name
+  CHARACTER(LEN=256)                        :: cldum              ! dummy char variable
+
+  TYPE(variable), DIMENSION(:), ALLOCATABLE :: stypvar            ! structure of output
+  TYPE(variable), DIMENSION(:), ALLOCATABLE :: stypvar2           ! structure of sub-domain counter output
+
+  LOGICAL                                   :: lfull     = .false.! full step  flag
+  LOGICAL                                   :: lchk               ! flag for missing files
+ 
+ !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  narg = iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage : cdfdegradw IN-Wfile IN-var ri rj [i0 j0]'
+     PRINT *,'       ... [-full]'
+     PRINT *,'       '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'       Degrad the horizontal resolution of NEMO W-grid ouput,       ' 
+     PRINT *,'       for each z-level and time step, with a ratio of ri along     '
+     PRINT *,'       x direction and rj along y direction. If specified, the input'
+     PRINT *,'       grid is considered starting from the indices i0 and j0.      ' 
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       IN-Wfile  : netcdf W-file.' 
+     PRINT *,'       IN-var    : name of netcdf variable to work with' 
+     PRINT *,'       ri        : degradation ratio for x-direction   ' 
+     PRINT *,'       rj        : degradation ratio for y-direction   ' 
+     PRINT *,'      '
+     PRINT *,'     OPTIONS : '
+     PRINT *,'       [i0 j0] : spatial indices from where starting the procedure   '
+     PRINT *,'                 of degradation.                                    ' 
+     PRINT *,'       [-full] : flag for full steps grid, instead of default partial'
+     PRINT *,'                 steps.'
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'       Files ', TRIM(cn_fhgr),', ', TRIM(cn_fzgr),', ', TRIM(cn_fmsk)
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file : degraded_cdfvar.nc '
+     PRINT *,'       netcdf file : flsdc.nc'
+     PRINT *,'      '
+    STOP
+  ENDIF
+
+  cglobal = 'Partial step computation'
+  ijarg = 1 ; ii = 0
+  DO WHILE ( ijarg <= narg )
+     CALL getarg(ijarg, cldum ) ; ijarg = ijarg + 1 
+     SELECT CASE (cldum) 
+     CASE ('-full' )
+        lfull = .true. 
+        cglobal = 'full step computation'
+     CASE DEFAULT 
+         ii=ii+1
+        SELECT CASE (ii) 
+        CASE ( 1 ) ; cf_wfil  = cldum 
+        CASE ( 2 ) ; cv_nam = cldum 
+        CASE ( 3 ) ; READ(cldum,*) nri  
+        CASE ( 4 ) ; READ(cldum,*) nrj  
+        CASE ( 5 ) ; READ(cldum,*) iimin
+        CASE ( 6 ) ; READ(cldum,*) ijmin
+        CASE DEFAULT
+          PRINT *, ' ERROR : Too many arguments ...'
+          STOP
+        END SELECT
+     END SELECT
+  END DO
+
+  lchk = chkfile(cn_fhgr)
+  lchk = chkfile(cn_fzgr) .OR. lchk
+  lchk = chkfile(cn_fmsk) .OR. lchk
+  lchk = chkfile(cf_wfil) .OR. lchk
+  IF ( lchk ) STOP ! missing file
+
+  cv_dep = 'none'
+  npiglo = getdim (cf_wfil, cn_x)
+  npjglo = getdim (cf_wfil, cn_y)
+  npk    = getdim (cf_wfil, cn_z, cdtrue=cv_dep, kstatus=ierr)
+
+  IF (ierr /= 0 ) THEN
+     npk   = getdim (cf_wfil, 'z', cdtrue=cv_dep, kstatus=ierr)
+     IF (ierr /= 0 ) THEN
+        npk   = getdim (cf_wfil, 'sigma', cdtrue=cv_dep, kstatus=ierr)
+        IF ( ierr /= 0 ) THEN
+           npk = getdim (cf_wfil, 'nav_lev', cdtrue=cv_dep, kstatus=ierr)
+           IF ( ierr /= 0 ) THEN
+              PRINT *,' assume file with no depth'
+              npk=0
+           ENDIF
+        ENDIF
+     ENDIF
+  ENDIF
+
+  npt    = getdim (cf_wfil, cn_t)
+  nvpk   = getvdim(cf_wfil, cv_nam)
+
+  IF (npk   == 0 ) THEN ; npk = 1;  ENDIF ! no depth dimension ==> 1 level
+  IF (iimin < 2 )  THEN
+     PRINT *,'iimin value is too low'
+     STOP
+  END IF
+  IF (ijmin  < 2 ) THEN
+     PRINT *,'ijmin value is too low'
+     STOP
+  END IF
+  npiglo = ( (npiglo - iimin ) / nri )*nri
+  npjglo = ( (npjglo - ijmin ) / nrj )*nrj
+  ikx = npiglo / nri
+  iky = npjglo / nrj
+
+  PRINT *,'ikx    : ',ikx
+  PRINT *,'iky    : ',iky
+
+  IF (nvpk == 2 ) npk = 1
+  ! IF (nvpk == 3 ) nvpk = npk
+
+  PRINT *, 'npiglo = ', npiglo
+  PRINT *, 'npjglo = ', npjglo
+  PRINT *, 'npk    = ', npk
+  PRINT *, 'npt    = ', npt
+  PRINT *, 'nvpk   = ', nvpk
+  PRINT *, 'depth dim name is ',TRIM(cv_dep)
+
+  ! Allocate arrays
+  ALLOCATE (zmask(npiglo,npjglo) )
+  ALLOCATE (zv(npiglo,npjglo) )
+  ALLOCATE (e1(npiglo,npjglo), e2(npiglo,npjglo) )
+  ALLOCATE (gdep (npk), e31d(npk), tim(npt) )
+  ALLOCATE (zdep(npk) )
+
+  cv_e1    = cn_ve1t
+  cv_e2    = cn_ve2t
+  cv_e3    = 'e3w_ps'
+  cv_e31d  = cn_ve3w
+  cv_msk = 'tmask'
+  cv_dep   = cn_gdepw
+ 
+  e1(:,:) = getvar  (cn_fhgr, cv_e1,  1,  npiglo, npjglo, kimin=iimin, kjmin=ijmin)
+  e2(:,:) = getvar  (cn_fhgr, cv_e2,  1,  npiglo, npjglo, kimin=iimin, kjmin=ijmin)
+  IF ( lfull )  e31d(:) = getvare3(cn_fzgr, cv_e31d, npk)
+  zdep(:) = getvare3(cn_fzgr, cv_dep, npk)
+  gdep(:) = zdep(  1  :npk)
+
+  ALLOCATE ( stypvar( 1 ), ipk( 1 ), id_varout( 1 ) )
+  ALLOCATE ( stypvar2( 1 ), id_varout2( 1 ) )
+  ALLOCATE ( rdumlon(ikx,iky), rdumlat(ikx,iky), rdummymean(ikx,iky) ) 
+  ALLOCATE ( nflsdc(ikx,iky) )
+  ALLOCATE ( glamf(npiglo+1,npjglo+1), gphif(npiglo+1,npjglo+1))
+
+  glamf = getvar(cn_fhgr, cn_glamf, 1, npiglo+1 , npjglo+1 , kimin=iimin-1 , kjmin=ijmin-1 )
+  gphif = getvar(cn_fhgr, cn_gphif, 1, npiglo+1 , npjglo+1 , kimin=iimin-1 , kjmin=ijmin-1 )
+  DO jj=1,iky
+     DO ji=1,ikx
+        rdumlat(ji,jj) = 0.5 * ( gphif((ji-1)*nri+1,(jj-1)*nrj+1) + gphif( ji   *nri+1,jj*nrj+1) )
+        rdumlon(ji,jj) = 0.5 * ( glamf( ji   *nri+1,(jj-1)*nrj+1) + glamf((ji-1)*nri+1,jj*nrj+1) )
+     END DO
+  END DO
+
+  ipk(:) = npk ! mean for each level
+
+  ierr=getvaratt (cf_wfil, cv_nam, clunits, zspval, cllong_name, clshort_name)
+
+  ! define new variables for output 
+  stypvar%rmissing_value    = 99999.
+  stypvar%scale_factor      = 1.
+  stypvar%add_offset        = 0.
+  stypvar%savelog10         = 0.
+  stypvar%conline_operation = 'N/A'
+
+  stypvar%cunits         = TRIM(clunits)
+  stypvar%valid_min      = -100000.
+  stypvar%valid_max      = 100000.
+  stypvar%cname          = 'degraded_'//TRIM(cv_nam)
+  stypvar%clong_name     = 'degraded '//TRIM(cllong_name)
+  stypvar%cshort_name    = 'degraded_'//TRIM(clshort_name)
+
+  stypvar2%rmissing_value    = 99999.
+  stypvar2%scale_factor      = 1.
+  stypvar2%add_offset        = 0.
+  stypvar2%savelog10         = 0.
+  stypvar2%conline_operation = 'N/A'
+
+  stypvar2%valid_min      = 0.
+  stypvar2%valid_max      = 100000.
+  stypvar2%cname          = 'flsdc'
+  stypvar2%clong_name     = 'fluid sub-domain counter'
+  stypvar2%cshort_name    = 'fdsdc'
+
+  IF ( nvpk == 2 ) THEN
+     stypvar%caxis       = 'TYX'
+     stypvar2%caxis      = 'YX'
+  ELSE
+     stypvar%caxis       = 'TZYX'
+     stypvar2%caxis      = 'ZYX'
+  END IF
+
+  ! create output fileset
+  cf_ncout  = 'degraded_'//TRIM(cv_nam)//'.nc'
+  cf_ncout2 = 'flsdc.nc'
+  ncout  = create      (cf_ncout ,   'none',  ikx,   iky,   npk, cdep=cv_dep)
+  ncout2 = create      (cf_ncout2,   'none',  ikx,   iky,   npk, cdep=cv_dep)
+  ierr  = createvar   (ncout ,      stypvar , 1 , ipk,   id_varout  , cdglobal=TRIM(cglobal) ) 
+  ierr  = createvar   (ncout2,      stypvar2, 1 , ipk,   id_varout2 , cdglobal=TRIM(cglobal) ) 
+  ierr  = putheadervar(ncout ,      cf_wfil,  ikx, iky, npk, pnavlon=rdumlon, pnavlat=rdumlat, pdep=gdep, cdep=cv_dep)
+  ierr  = putheadervar(ncout2,      cn_fmsk,  ikx, iky, npk, pnavlon=rdumlon, pnavlat=rdumlat, pdep=gdep, cdep=cv_dep)
+  tim   = getvar1d(cf_wfil, cn_vtimec, npt)
+  ierr  = putvar1d(ncout,  tim,       npt, 'T')
+
+  DO jk = 1, npk
+     ik = jk
+     ! Get variable v at ik
+     zmask(:,:) = getvar(cn_fmsk, cv_msk, ik, npiglo, npjglo, kimin=iimin, kjmin=ijmin          )
+     DO jt=1,npt
+        ! 
+        zv   (:,:) = getvar(cf_wfil,  cv_nam,   ik, npiglo, npjglo, kimin=iimin, kjmin=ijmin, ktime=jt)
+        DO jj=1,iky
+           DO ji=1,ikx
+              dvol = 0.d0
+              dsum = 0.d0
+              msks = 0
+              DO jrj=1,nrj
+                 DO jri=1,nri
+                    ix = (ji-1)*nri+jri
+                    iy = (jj-1)*nrj+jrj
+                    dvol2d = e1(ix,iy) * e2(ix,iy) * zmask(ix,iy)
+                    msks = msks + zmask(ix,iy)
+                    dvol = dvol + dvol2d
+                    dsum = dsum + zv(ix,iy) * dvol2d
+                 END DO
+              END DO
+              IF ( dvol > 0.d0 ) THEN
+                 rdummymean(ji,jj) = dsum/dvol
+              ELSE
+                 rdummymean(ji,jj) = 99999.
+              END IF
+              nflsdc(ji,jj) = msks
+           END DO
+        END DO
+        ierr = putvar(ncout , id_varout(1), rdummymean , jk, ikx, iky, ktime=jt )
+     END DO ! time loop
+     ierr = putvar(ncout2, id_varout2(1), DBLE(nflsdc), jk, ikx, iky )
+  END DO  
+
+  ierr = closeout(ncout )
+  ierr = closeout(ncout2)
+
+9004 FORMAT(f9.2,' ',i2,' ',f9.2)
+
+END PROGRAM cdfdegradw
diff --git a/cdfdifmask.f90 b/src/cdfdifmask.f90
similarity index 99%
rename from cdfdifmask.f90
rename to src/cdfdifmask.f90
index 3a03d32..5504967 100644
--- a/cdfdifmask.f90
+++ b/src/cdfdifmask.f90
@@ -99,6 +99,7 @@ PROGRAM cdfdifmask
      END DO  ! loop to next level
   END DO
 
+  ALLOCATE ( tim(1) )
   tim(:) = 0.
   ierr   = putvar1d(ncout, tim, 1, 'T')
   ierr   = closeout(ncout)
diff --git a/src/cdfdiv.f90 b/src/cdfdiv.f90
new file mode 100644
index 0000000..913417e
--- /dev/null
+++ b/src/cdfdiv.f90
@@ -0,0 +1,404 @@
+PROGRAM cdfdiv
+  !!======================================================================
+  !!                     ***  PROGRAM  cdfdiv  ***
+  !!=====================================================================
+  !!  ** Purpose : Compute the divergence for given gridU gridV files
+  !!               and variables
+  !!
+  !!  ** Method  : Use the same stencil than in NEMO code for computing
+  !!               vertical velocities
+  !!
+  !! History :  3.0  : 10/2011  : P. Mathiot : first version, based on cdfw.f90
+  !!                 : 05/2015  : J.M. Molines : revised version similar to cdfcurl
+  !!
+  !!----------------------------------------------------------------------
+
+  USE cdfio
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id$
+  !! Copyright (c) 2011, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)                           :: ji, jj, jk, jt     ! dummy loop index
+  INTEGER(KIND=4)                           :: npiglo, npjglo     ! size of the domain
+  INTEGER(KIND=4)                           :: npk, npt           ! size of the domain
+  INTEGER(KIND=4)                           :: nlev               ! number of output levels
+  INTEGER(KIND=4)                           :: narg, iargc        ! browse command line
+  INTEGER(KIND=4)                           :: ijarg              !
+  INTEGER(KIND=4)                           :: ncout, ierr        ! browse command line
+  INTEGER(KIND=4), DIMENSION(1)             :: ipk, id_varout     ! output variable properties
+  INTEGER(KIND=4), DIMENSION(:), ALLOCATABLE :: nilev             ! level to be processed
+
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e1v, e2u, e1t, e2t ! horizontql metrics
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e3u, e3v, e3t      ! vertical metrics
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: un, vn             ! velocity field
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zun, zvn           ! working arrays
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim, zdep, gdep    ! time counter
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: e31d               !  vertical metrics (full step)
+  REAL(KIND=4)                              :: zmask              ! mask at T point for -T option
+
+  REAL(KIND=8)                              :: dl_pi, dl_omega    ! 3.14159... and earth rotation rad/sec
+  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dhdivn             ! divergence
+  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dl_ff              ! Coriolis parameter at T point
+
+  CHARACTER(LEN=256)                        :: cf_ufil, cf_vfil   ! file names
+  CHARACTER(LEN=256)                        :: cf_out = 'curl.nc' ! output file name
+  CHARACTER(LEN=256)                        :: cv_u, cv_v         ! variable names
+  CHARACTER(LEN=256)                        :: cldum              ! dummy string
+
+  TYPE (variable), DIMENSION(1)             :: stypvar            ! structure for attibutes
+
+  LOGICAL                                   :: lforcing = .FALSE. ! forcing flag
+  LOGICAL                                   :: lchk     = .FALSE. ! flag for missing files
+  LOGICAL                                   :: lperio   = .FALSE. ! flag for E-W periodicity
+  LOGICAL                                   :: ldblpr   = .FALSE. ! flag for dble precision output
+  LOGICAL                                   :: lsurf    = .FALSE. ! flag for 1 lev on C grid.
+  LOGICAL                                   :: loverf   = .FALSE. ! flag for 1 lev on C grid.
+  LOGICAL                                   :: lfull=.FALSE.      ! full step flag
+
+  !!----------------------------------------------------------------------
+  CALL ReadCdfNames() 
+
+  narg = iargc()
+  IF ( narg < 8 ) THEN
+     PRINT *,' usage : cdfdiv -u U-file U-var -v V-file V-var -l levlist  [-8]...'
+     PRINT *,'           ... [-surf] [-overf] [-full] [-o OUT-file ]'
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'       Compute the divergence of the flow from the U and V velocity components'
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       -u U-file U-var : file and variable name for zonal component'
+     PRINT *,'       -v V-file V-var : file and variable name for meridional component'
+     PRINT *,'       -l levlist    : levels to be processed. If set to 0, assume forcing file'
+     PRINT *,'                in input. Example of recognized syntax :'
+     PRINT *,'                  -l "1,10,30"  or -l "1-20" or even -l "1-3,10-20,30-"'
+     PRINT *,'                  -l  1 . Note that -l "3-" set a levlist from 3 to the bottom'
+     PRINT * 
+     PRINT *,'     OPTIONS :'
+     PRINT *,'       -8 : save in double precision instead of standard simple precision.'
+     PRINT *,'       -surf : work with single level C-grid (not forcing)'
+     PRINT *,'       -overf : store the ratio curl/f where f is the coriolis parameter'
+     PRINT *,'       [ -full ] : in case of full step configuration. Default is partial step.'
+     PRINT *,'       -o OUT-file : specify output file name instead of ',TRIM(cf_out) 
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'        ', TRIM(cn_fhgr),' ',TRIM(cn_fzgr)
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file : ', TRIM(cf_out) 
+     PRINT *,'         variables : div units : s^-1'
+     PRINT *,'               or divoverf, no units (if -overf option)'
+     STOP
+  ENDIF
+
+  ijarg=1
+  DO WHILE ( ijarg <= narg ) 
+     CALL getarg(ijarg, cldum) ; ijarg=ijarg+1
+     SELECT CASE ( cldum )
+     CASE ('-u')
+        CALL getarg(ijarg, cf_ufil) ; ijarg=ijarg+1
+        CALL getarg(ijarg, cv_u   ) ; ijarg=ijarg+1
+     CASE ('-v')
+        CALL getarg(ijarg, cf_vfil) ; ijarg=ijarg+1
+        CALL getarg(ijarg, cv_v   ) ; ijarg=ijarg+1
+     CASE ('-l')
+        CALL getarg(ijarg, cldum) ; ijarg=ijarg+1 
+        CALL ParseLevel(cldum)  ! fills in array nilev(nlev)
+     CASE ('-8')
+        ldblpr = .true.
+     CASE ('-surf')
+        lsurf = .true.
+     CASE ('-overf')
+        loverf = .true.
+     CASE ('-full')
+        lfull = .true.
+     CASE ('-o')
+        CALL getarg(ijarg, cf_out) ; ijarg=ijarg+1
+     CASE DEFAULT
+        PRINT *,  TRIM(cldum), ' : unknown option '
+     END SELECT
+  ENDDO
+
+  lchk = chkfile(cn_fhgr ) .OR. lchk
+  lchk = chkfile(cn_fzgr ) .OR. lchk
+  lchk = chkfile(cf_ufil ) .OR. lchk
+  lchk = chkfile(cf_vfil ) .OR. lchk
+  IF ( lchk ) STOP ! missing files
+
+  ! define new variables for output
+  stypvar(1)%cname             = 'div'
+  stypvar(1)%cunits            = 's-1'
+  IF (loverf)  stypvar(1)%cname             = 'divoverf'
+  IF (loverf)  stypvar(1)%cunits            = '-'
+
+  stypvar(1)%cprecision        ='r4'
+  IF ( ldblpr )  stypvar(1)%cprecision     ='r8'
+  stypvar(1)%rmissing_value    = 0.
+  stypvar(1)%valid_min         = -1000.
+  stypvar(1)%valid_max         =  1000.
+  stypvar(1)%clong_name        = 'Divergence '
+  stypvar(1)%cshort_name       = 'div'
+  IF (loverf ) stypvar(1)%clong_name        = 'Divergence normalized by f'
+  IF (loverf ) stypvar(1)%cshort_name       = 'divoverf'
+  stypvar(1)%conline_operation = 'N/A'
+  stypvar(1)%caxis             = 'TYX'
+
+  ipk(1) = nlev  !  nlevel so far
+
+  npiglo = getdim(cf_ufil,cn_x)
+  npjglo = getdim(cf_ufil,cn_y)
+  npk    = getdim(cf_ufil,cn_z)
+  npt    = getdim(cf_ufil,cn_t) 
+
+  PRINT *, 'npiglo = ',npiglo
+  PRINT *, 'npjglo = ',npjglo
+  PRINT *, 'npk    = ',npk
+  PRINT *, 'npt    = ',npt
+  PRINT *, 'nlev   = ',nlev
+
+  !test if lev exists
+  IF ( (npk==0) .AND. (nlev > 0) .AND. .NOT. lsurf ) THEN
+     PRINT *, 'Problem : npk = 0 and lev > 0 STOP'
+     PRINT *, '  Use -surf option is dealing with single level file on C grid '
+     STOP
+  END IF
+
+  ! case of 1 level on C-grid
+  IF ( lsurf ) THEN
+     nlev=1
+     IF (ALLOCATED (nilev) ) THEN
+        DEALLOCATE(nilev) 
+     ENDIF
+     ALLOCATE(nilev(nlev) )
+     npk = 1 ; nilev(1) =1 
+  ENDIF
+
+  ! if forcing field 
+  IF ( nilev(1) == 0 .AND. npk==0 ) THEN
+     lforcing=.true.
+     npk = 1 ; nilev(1)=1
+     PRINT *, 'npk =0, assume 1'
+  END IF
+
+
+  IF ( npt==0 ) THEN
+     PRINT *, 'npt=0, assume 1'
+     npt=1
+  END IF
+  ! 
+  DO jk = 1, nlev
+   IF (nilev(jk) >= npk ) THEN
+     nlev=jk
+     EXIT
+   ENDIF
+  ENDDO
+  PRINT *, 'NLEV', nlev
+
+  ! Allocate the memory
+  ALLOCATE ( e1v(npiglo,npjglo), e2u(npiglo,npjglo) )
+  ALLOCATE ( e1t(npiglo,npjglo), e2t(npiglo,npjglo) )
+  ALLOCATE ( e3u(npiglo,npjglo), e3v(npiglo,npjglo), e3t(npiglo,npjglo) )
+
+  ALLOCATE ( un(npiglo,npjglo)  , vn(npiglo,npjglo)  )
+  ALLOCATE ( zun(npiglo,npjglo) , zvn(npiglo,npjglo) )
+  ALLOCATE ( dhdivn(npiglo,npjglo) )
+  ALLOCATE ( tim(npt) )
+  ALLOCATE ( gdep(nlev) , zdep(npk))
+  IF ( lfull ) ALLOCATE ( e31d (npk) )
+
+  e1v =  getvar(cn_fhgr, cn_ve1v, 1, npiglo, npjglo)
+  e1t =  getvar(cn_fhgr, cn_ve1t, 1, npiglo, npjglo)
+  e2u =  getvar(cn_fhgr, cn_ve2u, 1, npiglo, npjglo)
+  e2t =  getvar(cn_fhgr, cn_ve2t, 1, npiglo, npjglo)
+
+  ! use zun and zvn to store f latitude and longitude for output
+  zun = getvar(cn_fhgr, cn_glamt, 1, npiglo, npjglo)
+  zvn = getvar(cn_fhgr, cn_gphit, 1, npiglo, npjglo)
+
+  IF ( loverf ) THEN
+     ALLOCATE (dl_ff(npiglo,npjglo) )
+     dl_pi = acos(-1.d0)
+     dl_omega = 2* dl_pi/86400.d0
+     dl_ff = 2* dl_omega* sin ( zvn*dl_pi/180.d0 ) 
+  ENDIF
+  
+  ! fills in gdep
+  IF ( lforcing .OR. lsurf ) THEN
+     gdep(1)=0.
+  ELSE
+    zdep(:) = getvar1d(cf_ufil, cn_vdeptht, npk )
+    DO jk=1,nlev
+      gdep(jk) = zdep( nilev(jk) )
+    ENDDO
+  ENDIF
+  IF ( lfull ) e31d(:) = getvare3(cn_fzgr, cn_ve3t, npk)
+
+  ! look for  E-W periodicity
+  IF ( zun(1,1) == zun(npiglo-1,1) ) lperio = .TRUE.
+
+  ! create output fileset
+  PRINT *,' Create ',TRIM(cf_out)
+  ncout = create      (cf_out, cf_ufil, npiglo, npjglo, nlev, cdep=cn_vdeptht                    )
+  PRINT *,' Create variables in  ',TRIM(cf_out)
+  ierr  = createvar   (ncout , stypvar, 1,      ipk,    id_varout                                )
+  PRINT *,' Fill header variables  in  ',TRIM(cf_out)
+  ierr  = putheadervar(ncout,  'dummy', npiglo, npjglo, nlev, pnavlon=zun, pnavlat=zvn, pdep=gdep)
+  PRINT *,' Output file ready for write !'
+
+  tim  = getvar1d(cf_ufil, cn_vtimec, npt      )
+  ierr = putvar1d(ncout,   tim,       npt,  'T')
+
+  DO jt=1,npt
+     IF (MOD(jt,100)==0 ) PRINT *, jt,'/',npt
+     DO jk = 1, nlev
+
+        zun(:,:) =  getvar(cf_ufil, cv_u, nilev(jk) ,npiglo,npjglo, ktime=jt)
+        zvn(:,:) =  getvar(cf_vfil, cv_v, nilev(jk) ,npiglo,npjglo, ktime=jt)
+
+        IF ( lfull ) THEN
+           e3u(:,:) = e31d(jk)
+           e3v(:,:) = e31d(jk)
+           e3t(:,:) = e31d(jk)
+        ELSE
+           ! e3 metrics at level jk ( Partial steps)
+           e3u(:,:) = getvar(cn_fzgr, 'e3u_ps', jk, npiglo, npjglo, ldiom=.TRUE.)
+           e3v(:,:) = getvar(cn_fzgr, 'e3v_ps', jk, npiglo, npjglo, ldiom=.TRUE.)
+           e3t(:,:) = getvar(cn_fzgr, 'e3t_ps', jk, npiglo, npjglo, ldiom=.TRUE.)
+        ENDIF
+
+
+        IF ( lforcing ) THEN ! for forcing file u and v are on the A grid
+           DO ji=1, npiglo-1
+              un(ji,:) = 0.5*(zun(ji,:) + zun(ji+1,:))
+           END DO
+           !
+           DO jj=1, npjglo-1
+              vn(:,jj) = 0.5*(zvn(:,jj) + zvn(:,jj+1))
+           END DO
+           ! end compute u and v on U and V point
+        ELSE
+           un(:,:) = zun(:,:)
+           vn(:,:) = zvn(:,:)
+        END IF
+
+        dhdivn(:,:) = 0.d0
+        DO jj = 2, npjglo -1
+           DO ji = 2, npiglo -1
+              dhdivn(ji,jj) =   &
+                &  (  e2u(ji,  jj  )*e3u(ji  ,jj  ) * un(ji  ,jj  )*1.d0 - &
+                &     e2u(ji-1,jj  )*e3u(ji-1,jj  ) * un(ji-1,jj  )*1.d0   &
+                &   + e1v(ji  ,jj  )*e3v(ji  ,jj  ) * vn(ji  ,jj  )*1.d0 - &
+                &     e1v(ji  ,jj-1)*e3v(ji  ,jj-1) * vn(ji  ,jj-1)*1.d0  )&
+                & / ( e1t(ji,jj)*e2t(ji,jj) * e3t(ji,jj) )
+           END DO
+        END DO
+
+        IF ( lperio ) dhdivn(npiglo,:) = dhdivn(2, :)
+
+        ! write dhdivn on file at level k and at time jt
+        IF ( loverf ) THEN
+           WHERE (dl_ff /= 0.d0) dhdivn=dhdivn/dl_ff
+        ENDIF
+
+        ierr = putvar(ncout, id_varout(1), dhdivn, nilev(jk), npiglo, npjglo, ktime=jt)
+     ENDDO
+  END DO
+  ierr = closeout(ncout)
+
+CONTAINS
+  SUBROUTINE ParseLevel( cdum )
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE ParsLevel  ***
+    !!
+    !! ** Purpose :  Parse a string representing a level list with no separator
+    !!               or , or - as separator 
+    !!
+    !! ** Method  :   1,3,5 => list = (1,3,5)
+    !!                1-4   => liste = ( 1,2,3,4) 
+    !!                1-4,6-8   => liste = ( 1,2,3,4,6,7,8) 
+    !!                10-      => liste = (10,11,12,...bottom)
+    !!                Allocate and fill nilev array with respective levels
+    !!
+    !!----------------------------------------------------------------------
+    CHARACTER(LEN=*), INTENT (in ) :: cdum
+
+    INTEGER(KIND=4)                 :: jc, jk
+    INTEGER(KIND=4)                 :: ilength, ik1, ik2
+    INTEGER(KIND=4)                 :: icomma, idash, ipos, ipos1
+    INTEGER(KIND=4), DIMENSION(350) :: ilev
+    CHARACTER(LEN=256) :: cldum
+    CHARACTER(LEN=80), DIMENSION(:), ALLOCATABLE :: clblk
+    !!----------------------------------------------------------------------
+    ilength=LEN(TRIM(cdum) )
+
+    ! look for , and -
+    icomma = 0 ; idash = 0
+    DO jc=1,ilength
+       IF ( cdum(jc:jc) == ',' ) THEN
+          icomma = icomma + 1
+       ELSE IF ( cdum(jc:jc) == '-' ) THEN
+          idash = idash + 1
+       ENDIF
+    END DO
+
+    ! no dash nor comma
+    IF (icomma == 0 .AND. idash == 0 ) THEN
+       nlev=1
+       ALLOCATE ( nilev(nlev) )
+       READ(cdum,*) nilev(1)
+       RETURN
+    ENDIF
+    ! look for the number of blocks (between commas)
+    cldum=cdum
+    ALLOCATE (clblk(icomma+1))
+
+    ipos1=1
+    DO jc=1,icomma
+       ipos=INDEX(cldum ,",")
+       clblk(jc)=cldum(1:ipos-1)
+       ipos1=ipos+1
+       cldum=cldum(ipos1:)
+    ENDDO
+    clblk(icomma+1)=cldum
+
+    ! now parse block
+    nlev=0
+    DO jc=1,icomma+1
+       ipos=INDEX(clblk(jc),"-")
+       IF ( ipos == 0 ) THEN
+          nlev=nlev+1
+          READ(clblk(jc),* ) ilev(nlev) 
+       ELSE IF ( ipos == LEN(TRIM((clblk(jc)))) ) THEN
+          READ(clblk(jc)(1:ipos-1),*) ik1
+          ik2=300  ! use 300 as a maximum mean while we wait for npk
+          PRINT *,' BINGO !', ik1, ik2
+          DO jk=ik1,ik2
+             nlev=nlev+1
+             ilev(nlev)=jk
+          ENDDO
+       ELSE
+          READ(clblk(jc)(1:ipos-1),*) ik1
+          READ(clblk(jc)(ipos+1: ),*) ik2
+          DO jk=ik1,ik2
+             nlev=nlev+1
+             ilev(nlev)=jk
+          ENDDO
+       ENDIF
+    ENDDO
+    ALLOCATE (nilev(nlev) )
+    nilev(:)=ilev(1:nlev)
+
+    DEALLOCATE( clblk)
+
+
+  END SUBROUTINE ParseLevel
+
+END PROGRAM cdfdiv
+
+
diff --git a/src/cdfeddyscale.f90 b/src/cdfeddyscale.f90
new file mode 100644
index 0000000..673f4d6
--- /dev/null
+++ b/src/cdfeddyscale.f90
@@ -0,0 +1,227 @@
+PROGRAM cdfeddyscale
+  !!======================================================================
+  !!                     ***  PROGRAM  cdfeddyscale  ***
+  !!=====================================================================
+  !!  ** Purpose : Compute: -the Taylor scale or large scale eddy (lambda1)
+  !!                        -the small scale eddy (lambda2) 
+  !!                        -and the inertial range (scar) on F-points
+  !!               lambda1 = sqrt(mean Kinetic Energie / Enstrophy)
+  !!               lambda2 = sqrt(Enstrophy / Palinstrophy)
+  !!               scar    = lambda1 / lambda2
+  !!
+  !!               Enstrophy = 1/2 * ( mean((RV)^2) )
+  !!               Palinstrophy = 1/2 * ( mean((dx(RV))^2 + (dy(RV))^2) ) 
+  !!
+  !!  ** Method  : Use the mean of the variables (vozocrtx2 + vomecrty2), socurl2, 
+  !!               (sodxcurl2 + sodycurl2) of the cdfeddyscale_pass1.f90  
+  !!               
+  !!  ** Warning : - the square of curl socurl2 is on F-points, 
+  !!               - vozocrtx2, vomecrty2, sodxcurl2 and sodycurl2 are on UV-points
+  !!              
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2013
+  !! $Id$
+  !! Copyright (c) 2013, C. Q. C. AKUETEVI & J.-M. Molines
+  !! Software governed by the CeCILL licence
+  !! (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)                           :: ji, jj, jt         ! dummy loop index
+  INTEGER(KIND=4)                           :: ilev               ! level to be processed
+  INTEGER(KIND=4)                           :: npiglo, npjglo     ! size of the domain
+  INTEGER(KIND=4)                           :: npk, npt           ! size of the domain
+  INTEGER(KIND=4)                           :: narg, iargc        ! browse command line
+  INTEGER(KIND=4)                           :: ncout, ierr        ! browse command line
+  INTEGER(KIND=4), DIMENSION(3)             :: ipk, id_varout     ! output variable properties
+
+  REAL(KIND=4), DIMENSION(1)                :: tim                ! time counter in output file
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zun, zvn           ! working arrays
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: rotn2              ! square curl
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zdxrotn2, zdyrotn2 ! square curl gradient components
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: vozocrtx2          ! square of velocity components
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: vomecrty2          ! square of velocity components
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zmke               ! mean kinetic energy
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: ens                ! enstrophy
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zpal               ! palinstrophy
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zlambda1           ! Taylor or large scale eddy
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zlambda2           ! small scale eddy
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: scar               ! inertial range
+
+  CHARACTER(LEN=256)                        :: cf_meanfil   ! file names
+  CHARACTER(LEN=256)                        :: cf_out = 'lambda.nc' ! output file name
+  CHARACTER(LEN=256)                        :: cldum              ! dummy string
+
+  TYPE (variable), DIMENSION(3)             :: stypvar            ! structure for attibutes
+
+  LOGICAL                                   :: lforcing = .FALSE. ! forcing flag
+  LOGICAL                                   :: lchk     = .FALSE. ! flag for missing files
+  LOGICAL                                   :: lperio   = .FALSE. ! flag for E-W periodicity
+  !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  narg = iargc()
+  IF ( narg /= 1 ) THEN
+     PRINT *,' usage : cdfeddyscale mean-cdfeddyscale_pass1-file'
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'     Compute: -the Taylor scale or large scale eddy (lambda1)'
+     PRINT *,'              -the small scale eddy (lambda2)'
+     PRINT *,'              -and the inertial range (scar) on F-points'
+     PRINT *,'      '
+     PRINT *,'     lambda1 = sqrt(mean Kinetic Energie / Enstrophy)'
+     PRINT *,'     lambda2 = sqrt(Enstrophy / Palinstrophy)'
+     PRINT *,'     Inertial Range    = lambda1 / lambda2'
+     PRINT *,'      ' 
+     PRINT *,'     Enstrophy = 1/2 * ( mean((RV)^2) )'
+     PRINT *,'     Palinstrophy = 1/2 * ( mean((dx(RV))^2 + (dy(RV))^2) )'
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'     mean-cdfeddyscale_pass1-file : mean of the terms compute by' 
+     PRINT *,'     the program cdfeddyscale_pass1'
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file : ', TRIM(cf_out)
+     PRINT *,'         variables : solambda1 (m), solambda2 (m), soscar'
+     PRINT *,'      '
+     PRINT *,'     SEE ALSO :'
+     PRINT *,'       cdfeddyscale_pass1 '
+     STOP
+  ENDIF
+
+  CALL getarg(1, cf_meanfil)
+
+  lchk = chkfile(cf_meanfil ) .OR. lchk
+  IF ( lchk ) STOP ! missing files
+
+  npiglo = getdim(cf_meanfil,cn_x)
+  npjglo = getdim(cf_meanfil,cn_y)
+
+  PRINT *, 'npiglo = ',npiglo
+  PRINT *, 'npjglo = ',npjglo
+
+  ! Allocate the memory
+  ALLOCATE ( rotn2(npiglo,npjglo)                                )
+  ALLOCATE ( zdxrotn2(npiglo,npjglo)  , zdyrotn2(npiglo,npjglo)  )
+  ALLOCATE ( vozocrtx2(npiglo,npjglo) , vomecrty2(npiglo,npjglo) )
+  ALLOCATE ( zmke(npiglo,npjglo)                                 )
+  ALLOCATE ( ens(npiglo,npjglo)                                  )
+  ALLOCATE ( zpal(npiglo,npjglo)                                 )
+  ALLOCATE ( zlambda1(npiglo,npjglo)   , zlambda2(npiglo,npjglo) )
+  ALLOCATE ( scar(npiglo,npjglo)                                 )
+
+  CALL CreateOutputFile
+  
+  !load the mean variables
+  rotn2(:,:)     =  getvar(cf_meanfil, 'socurl2'  , 1,npiglo,npjglo )
+  zdxrotn2(:,:)  =  getvar(cf_meanfil, 'sodxcurl2', 1,npiglo,npjglo )
+  zdyrotn2(:,:)  =  getvar(cf_meanfil, 'sodycurl2', 1,npiglo,npjglo )
+  vozocrtx2(:,:) =  getvar(cf_meanfil, 'vozocrtx2', 1,npiglo,npjglo )
+  vomecrty2(:,:) =  getvar(cf_meanfil, 'vomecrty2', 1,npiglo,npjglo )
+
+  ! Enstrophy
+  ens(:,:) = 0.5 * rotn2(:,:)
+
+  ! compute the Kinetic Energy on F-points
+  zmke = -9999.
+  DO jj = 1, npjglo-1
+     DO ji = 1, npiglo-1   ! vector opt.
+        zmke(ji,jj) =  0.25 * (vozocrtx2(ji,jj+1) + vozocrtx2(ji,jj))   &
+                   & + 0.25 * (vomecrty2(ji+1,jj) + vomecrty2(ji,jj))   
+     END DO
+  END DO
+
+  ! compute the Palinstrophy on  F-points
+  zpal = -9999.
+  DO jj = 1, npjglo-1 
+     DO ji = 1, npiglo-1   ! vector opt.
+        zpal(ji,jj) =  0.25 * (zdxrotn2(ji+1,jj) + zdxrotn2(ji,jj))  &
+                   & + 0.25 * (zdyrotn2(ji,jj+1) + zdyrotn2(ji,jj))   
+     END DO
+  END DO
+
+  ! compute the Taylor and small scale eddy
+  zlambda1(:,:) = 0.
+  zlambda2(:,:) = 0.
+  WHERE( ens > 0.  ) zlambda1(:,:) = SQRT ( zmke(:,:)/ens(:,:))
+  WHERE( zpal > 0. ) zlambda2(:,:) = SQRT ( ens(:,:)/zpal(:,:))
+
+  ! compute the Inertial Range
+  scar(:,:) = 0. 
+  WHERE( zlambda2 > 0. ) scar(:,:) = zlambda1(:,:)/zlambda2(:,:) 
+       
+  ! write zlambda1 on file 
+  ierr = putvar(ncout, id_varout(1), zlambda1, 1, npiglo, npjglo )
+
+  ! write zlamdba2 on file
+  ierr = putvar(ncout, id_varout(2), zlambda2, 1, npiglo, npjglo )
+  
+  ! write scar on file
+  ierr = putvar(ncout, id_varout(3), scar,     1, npiglo, npjglo ) 
+  
+  ierr = closeout(ncout)
+
+  CONTAINS
+
+  SUBROUTINE CreateOutputFile
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE CreateOutputFile  ***
+    !!
+    !! ** Purpose :  Create Output file 
+    !!
+    !! ** Method  :  Use global variable 
+    !!
+    !!----------------------------------------------------------------------
+
+  ! define new variables for output
+  ! Taylor or large scale eddy F point
+  ipk(1)                       = 1   !2D
+  stypvar(1)%cname             = 'solambda1'
+  stypvar(1)%cunits            = 'm'
+  stypvar(1)%rmissing_value    = 0.
+  stypvar(1)%valid_min         = 0.
+  stypvar(1)%valid_max         =  100000.
+  stypvar(1)%clong_name        = 'Taylor_large_eddy_scale (lambda1)'
+  stypvar(1)%cshort_name       = 'solambda1'
+  stypvar(1)%conline_operation = 'N/A'
+  stypvar(1)%caxis             = 'TYX'
+  
+  ! Small scale eddy F point
+  ipk(2)                       = 1   !2D
+  stypvar(2)%cname             = 'solambda2'
+  stypvar(2)%cunits            = 'm'
+  stypvar(2)%rmissing_value    = 0.
+  stypvar(2)%valid_min         = 0.
+  stypvar(2)%valid_max         =  100000.
+  stypvar(2)%clong_name        = 'Small scale eddy (lambda2)'
+  stypvar(2)%cshort_name       = 'solambda2'
+  stypvar(2)%conline_operation = 'N/A'
+  stypvar(2)%caxis             = 'TYX'
+
+  ! Inertial Range F point
+  ipk(3)                       = 1   !2D
+  stypvar(3)%cname             = 'soscar'
+  stypvar(3)%cunits            = ''
+  stypvar(3)%rmissing_value    = 0.
+  stypvar(3)%valid_min         = 0.
+  stypvar(3)%valid_max         =  20.
+  stypvar(3)%clong_name        = 'Inertial range (scar)'
+  stypvar(3)%cshort_name       = 'soscar'
+  stypvar(3)%conline_operation = 'N/A'
+  stypvar(3)%caxis             = 'TYX'
+
+  ! create output fileset
+  ncout = create      (cf_out, cf_meanfil, npiglo, npjglo, 0)
+  ierr  = createvar   (ncout , stypvar, 3,      ipk,    id_varout)
+  ierr  = putheadervar(ncout,  cf_meanfil, npiglo, npjglo, 0 )
+
+  tim  = getvar1d(cf_meanfil, cn_vtimec, 1      )
+  ierr = putvar1d(ncout,      tim,       1,  'T')
+
+  END SUBROUTINE CreateOutputFile
+
+END PROGRAM cdfeddyscale
+
diff --git a/src/cdfeddyscale_pass1.f90 b/src/cdfeddyscale_pass1.f90
new file mode 100644
index 0000000..5cfe414
--- /dev/null
+++ b/src/cdfeddyscale_pass1.f90
@@ -0,0 +1,398 @@
+PROGRAM cdfeddyscale_pass1
+   !!======================================================================
+   !!                     ***  PROGRAM  cdfeddyscale_pass1  ***
+   !!=====================================================================
+   !!  ** Purpose : Compute: - the curl and the square of curl on F-points, 
+   !!                        - the gradient components of the curl and the
+   !!                          square of the gradient components on UV-points
+   !!                        - the square of velocity components on UV-points 
+   !!               for given gridU gridV files and variables.
+   !!               These terms will used to compute the Taylor scale or large
+   !!               scale eddy (lambda1) and the small scale eddy (lambda2) 
+   !!               in the program cdflambda.f90.
+   !!
+   !!  ** Method  : Use the same algorithm than NEMO
+   !!
+   !!----------------------------------------------------------------------
+   USE cdfio
+   USE modcdfnames
+   !!----------------------------------------------------------------------
+   !! CDFTOOLS_3.0 , MEOM 2013
+   !! $Id$
+   !! Copyright (c) 2013, C. Q. C. Akuetevi & J.-M. Molines
+   !! Software governed by the CeCILL licence
+   !! (Licence/CDFTOOLSCeCILL.txt)
+   !!----------------------------------------------------------------------
+   IMPLICIT NONE
+   ! index of output variables
+   INTEGER(KIND=4),                PARAMETER :: jp_nvar=8
+   INTEGER(KIND=4),                PARAMETER :: jp_curl=1, jp_curl2=2, jp_dxcurl=3, jp_dycurl=4
+   INTEGER(KIND=4),                PARAMETER :: jp_dxcurl2=5, jp_dycurl2=6, jp_u2=7, jp_v2=8
+
+   INTEGER(KIND=4)                           :: ji, jj, jt         ! dummy loop index
+   INTEGER(KIND=4)                           :: ilev               ! level to be processed
+   INTEGER(KIND=4)                           :: npiglo, npjglo     ! size of the domain
+   INTEGER(KIND=4)                           :: npk, npt           ! size of the domain
+   INTEGER(KIND=4)                           :: narg, iargc        ! browse command line
+   INTEGER(KIND=4)                           :: ncout, ierr        ! browse command line
+   INTEGER(KIND=4), DIMENSION(jp_nvar)       :: ipk, id_varout     ! output variable properties
+
+   REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim                ! time counter
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e1f, e2f           ! F-grid metrics
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e1u, e2u           ! zonal horizontal metrics
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e1v, e2v           ! meridional horizontal metrics
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: un, vn             ! velocity field
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zun, zvn           ! working arrays
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: fmask              ! fmask
+
+   REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dl_rotn, dl_rotn2  ! curl and square curl
+   REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dxrotn, dyrotn     ! curl gradient components
+   REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dxrotn2, dyrotn2   ! square curl gradient components
+   REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dl_vozocrtx2       ! square of velocity components
+   REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dl_vomecrty2       ! square of velocity components
+
+
+   CHARACTER(LEN=256)                        :: cf_ufil, cf_vfil   ! file names
+   CHARACTER(LEN=256)                        :: cf_out = 'lambda_int.nc' ! output file name
+   CHARACTER(LEN=256)                        :: cv_u, cv_v         ! variable names
+   CHARACTER(LEN=256)                        :: cldum              ! dummy string
+
+   TYPE (variable), DIMENSION(jp_nvar)       :: stypvar            ! structure for attibutes
+
+   LOGICAL                                   :: lforcing = .FALSE. ! forcing flag
+   LOGICAL                                   :: lchk     = .FALSE. ! flag for missing files
+   LOGICAL                                   :: lperio   = .FALSE. ! flag for E-W periodicity
+   !!----------------------------------------------------------------------
+   CALL ReadCdfNames()
+
+   narg = iargc()
+   IF ( narg /= 5 ) THEN
+      PRINT *,' usage : cdfeddyscale_pass1 U-file V-file U-var V-var lev'
+      PRINT *,'      '
+      PRINT *,'     PURPOSE :'
+      PRINT *,'     Compute: - the curl and the square of curl on F-points,' 
+      PRINT *,'              - the gradient components of the curl and the'
+      PRINT *,'                square of the gradient components on UV-points,'
+      PRINT *,'              - the square of velocity components on UV-points,' 
+      PRINT *,'     for given gridU gridV files and variables. These variables are required'
+      PRINT *,'     for computing eddy scales with cdfeddyscale. Therefore this program is'
+      PRINT *,'     the first step in computing the eddy scales.'
+      PRINT *,'     '
+      PRINT *,'        These terms will used to compute the Taylor scale or large'
+      PRINT *,'     scale eddy (lambda1) and the small scale eddy (lambda2) in'
+      PRINT *,'     the program cdfeddyscale.'
+      PRINT *,'      '
+      PRINT *,'     ARGUMENTS :'
+      PRINT *,'       U-file : zonal component of the vector field.'
+      PRINT *,'       V-file : meridional component of the vector field.'
+      PRINT *,'       U-var  : zonal component variable name'
+      PRINT *,'       V-var  : meridional component variable name.'
+      PRINT *,'       lev    : level to be processed. If set to 0, assume forcing file '
+      PRINT *,'                in input.'
+      PRINT *,'      '
+      PRINT *,'     REQUIRED FILES :'
+      PRINT *,'        ', TRIM(cn_fhgr)
+      PRINT *,'      '
+      PRINT *,'     OUTPUT : '
+      PRINT *,'       netcdf file : ', TRIM(cf_out)
+      PRINT *,'         variables : socurl (s^-1), socurl2 (s^-2)'
+      PRINT *,'         variables : sodxcurl, sodycurl (s^-1.m^-1)'
+      PRINT *,'         variables : sodxcurl2, sodycurl2 (s^-2.m^-2)'
+      PRINT *,'         variables : vozocrtx2, vomecrty2 (m^2.s^-2)'
+      PRINT *,'         WARNING : variables in the output file are not located at the same'
+      PRINT *,'                 C-grid point.'
+      PRINT *,'      '
+      PRINT *,'     SEE ALSO : '
+      PRINT *,'        cdfeddyscale'
+      STOP
+   ENDIF
+
+
+   CALL getarg(1, cf_ufil)
+   CALL getarg(2, cf_vfil)
+   CALL getarg(3, cv_u   )
+   CALL getarg(4, cv_v   )
+   CALL getarg(5, cldum  ) ;  READ(cldum,*) ilev
+
+   lchk = chkfile(cn_fhgr ) .OR. lchk
+   lchk = chkfile(cf_ufil ) .OR. lchk
+   lchk = chkfile(cf_vfil ) .OR. lchk
+   IF ( lchk ) STOP ! missing files
+
+   ! load the dimension
+   npiglo = getdim(cf_ufil,cn_x)
+   npjglo = getdim(cf_ufil,cn_y)
+   npk    = getdim(cf_ufil,cn_z)
+   npt    = getdim(cf_ufil,cn_t)
+
+   PRINT *, 'npiglo = ',npiglo
+   PRINT *, 'npjglo = ',npjglo
+   PRINT *, 'npk    = ',npk
+   PRINT *, 'npt    = ',npt
+   PRINT *, 'ilev   = ',ilev
+
+   !test if lev exists
+   IF ( (npk==0) .AND. (ilev > 1) ) THEN
+      PRINT *, 'Problem : npk = 0 and lev > 0 STOP'
+      STOP
+   ELSE
+      npk = 1
+   END IF
+
+   ! if forcing field 
+   IF ( ilev==0 .AND. npk==0 ) THEN
+      lforcing=.TRUE.
+      npk = 1 ; ilev=1
+      PRINT *, 'npk =0, assume 1'
+   END IF
+
+   IF ( npt==0 ) THEN
+      PRINT *, 'npt=0, assume 1'
+      npt=1
+   END IF
+   ! check files and determines if the curl will be 2D of 3D
+
+   ! Allocate the memory
+   ALLOCATE ( e1u(npiglo,npjglo)       , e2u(npiglo,npjglo)       )  
+   ALLOCATE ( e1v(npiglo,npjglo)       , e2v(npiglo,npjglo)       )
+   ALLOCATE ( e1f(npiglo,npjglo)       , e2f(npiglo,npjglo)       )
+   ALLOCATE ( un(npiglo,npjglo)        , vn(npiglo,npjglo)        )
+   ALLOCATE ( zun(npiglo,npjglo)       , zvn(npiglo,npjglo)       )
+   ALLOCATE ( fmask(npiglo,npjglo)                                )
+   ALLOCATE ( tim(npt)                                            )
+   ALLOCATE ( dl_rotn(npiglo,npjglo)   , dl_rotn2(npiglo,npjglo)  )
+   ALLOCATE ( dxrotn(npiglo,npjglo)    , dyrotn(npiglo,npjglo)    )
+   ALLOCATE ( dxrotn2(npiglo,npjglo)   , dyrotn2(npiglo,npjglo)   )
+   ALLOCATE ( dl_vozocrtx2(npiglo,npjglo)                         )
+   ALLOCATE ( dl_vomecrty2(npiglo,npjglo)                         )
+
+
+   ! Read the metrics from the mesh_hgr file
+   e1u =  getvar(cn_fhgr, cn_ve1u, 1, npiglo, npjglo)
+   e2u =  getvar(cn_fhgr, cn_ve2u, 1, npiglo, npjglo)
+   e1v =  getvar(cn_fhgr, cn_ve1v, 1, npiglo, npjglo)
+   e2v =  getvar(cn_fhgr, cn_ve2v, 1, npiglo, npjglo)
+   e1f =  getvar(cn_fhgr, cn_ve1f, 1, npiglo, npjglo)
+   e2f =  getvar(cn_fhgr, cn_ve2f, 1, npiglo, npjglo)
+
+   CALL CreateOutputFile 
+
+   DO jt=1,npt
+      IF (MOD(jt,100)==0 ) PRINT *, jt,'/',npt
+      ! if files are forcing fields
+      zun(:,:) =  getvar(cf_ufil, cv_u, ilev ,npiglo,npjglo, ktime=jt)
+      zvn(:,:) =  getvar(cf_vfil, cv_v, ilev ,npiglo,npjglo, ktime=jt)
+
+      IF ( lforcing ) THEN ! for forcing file u and v are on the A grid
+         DO ji=1, npiglo-1
+            un(ji,:) = 0.5*(zun(ji,:) + zun(ji+1,:))
+         END DO
+         !
+         DO jj=1, npjglo-1
+            vn(:,jj) = 0.5*(zvn(:,jj) + zvn(:,jj+1))
+         END DO
+         ! end compute u and v on U and V point
+      ELSE
+         un(:,:) = zun(:,:)
+         vn(:,:) = zvn(:,:)
+      END IF
+
+      ! compute the mask
+      IF ( jt==1 ) THEN
+         DO jj = 1, npjglo - 1
+            DO ji = 1, npiglo - 1
+               fmask(ji,jj)=0.
+               fmask(ji,jj)= un(ji,jj)*un(ji,jj+1) * vn(ji,jj)*vn(ji+1,jj)
+               IF (fmask(ji,jj) /= 0.) fmask(ji,jj)=1.
+            ENDDO
+         ENDDO
+      END IF
+      ! compute the curl
+      dl_rotn(:,:) = 0.d0
+      DO jj = 1, npjglo -1
+         DO ji = 1, npiglo -1   ! vector opt.
+            dl_rotn(ji,jj) = (  e2v(ji+1,jj  ) * vn(ji+1,jj  ) - e2v(ji,jj) *vn(ji,jj) &
+                 &         - e1u(ji  ,jj+1) * un(ji  ,jj+1) + e1u(ji,jj) *un(ji,jj)  ) &
+                 &         * fmask(ji,jj) / ( e1f(ji,jj) * e2f(ji,jj) )
+         END DO
+      END DO
+
+      IF ( lperio ) dl_rotn(npiglo,:) = dl_rotn(2, :)
+
+      ! compute the square curl
+      dl_rotn2(:,:) = dl_rotn(:,:) * dl_rotn(:,:)
+
+      ! compute the gradient components
+      dxrotn(:,:) = 0.d0
+      dyrotn(:,:) = 0.d0
+      DO jj = 2, npjglo 
+         DO ji = 2, npiglo    ! vector opt.
+            dxrotn(ji,jj) = (dl_rotn(ji,jj) - dl_rotn(ji-1,jj))/e1v(ji,jj)
+            dyrotn(ji,jj) = (dl_rotn(ji,jj) - dl_rotn(ji,jj-1))/e2u(ji,jj)
+         END DO
+      END DO
+
+      IF ( lperio ) dxrotn(1,:) = dxrotn(npiglo-1, :)
+      IF ( lperio ) dyrotn(1,:) = dyrotn(npiglo-1, :)
+
+      ! compute the square module of the gradient
+      dxrotn2(:,:) = dxrotn(:,:) * dxrotn(:,:)
+      dyrotn2(:,:) = dyrotn(:,:) * dyrotn(:,:)
+
+      ! compute the square of the velocity components
+      dl_vozocrtx2(:,:) = zun(:,:) * zun(:,:) 
+      dl_vomecrty2(:,:) = zvn(:,:) * zvn(:,:)
+
+      ! write dl_rotn on file at level k and at time jt
+      ierr = putvar(ncout, id_varout(jp_curl),    REAL(dl_rotn),  1, npiglo, npjglo, ktime=jt)
+
+      ! write dl_rotn2 on file at level k and at time jt
+      ierr = putvar(ncout, id_varout(jp_curl2),   REAL(dl_rotn2), 1, npiglo, npjglo, ktime=jt)
+
+      ! write dxrotn on file at level k and at time jt
+      ierr = putvar(ncout, id_varout(jp_dxcurl),  REAL(dxrotn),   1, npiglo, npjglo, ktime=jt)
+
+      ! write dyrotn on file at level k and at time jt
+      ierr = putvar(ncout, id_varout(jp_dycurl),  REAL(dyrotn),   1, npiglo, npjglo, ktime=jt)
+
+      ! write dxrotn2 on file at level k and at time jt
+      ierr = putvar(ncout, id_varout(jp_dxcurl2), REAL(dxrotn2),  1, npiglo, npjglo, ktime=jt)
+
+      ! write dyrotn2 on file at level k and at time jt
+      ierr = putvar(ncout, id_varout(jp_dycurl2), REAL(dyrotn2),  1, npiglo, npjglo, ktime=jt)
+
+      ! write dl_vozocrtx2 on file at level k and at time jt
+      ierr = putvar(ncout, id_varout(jp_u2),  REAL(dl_vozocrtx2), 1, npiglo, npjglo, ktime=jt)
+
+      ! write dl_vozocrtx2 on file at level k and at time jt
+      ierr = putvar(ncout, id_varout(jp_v2),  REAL(dl_vomecrty2), 1, npiglo, npjglo, ktime=jt)
+
+   END DO
+   ierr = closeout(ncout)
+CONTAINS
+
+   SUBROUTINE CreateOutputFile
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE CreateOutputFile  ***
+      !!
+      !! ** Purpose :  Create output file 
+      !!
+      !! ** Method  :   Use global program variables 
+      !!
+      !!----------------------------------------------------------------------
+
+      ! define new variables for output
+      ! Relative Vorticity F point
+      ipk(jp_curl)                       = 1   !2D
+      stypvar(jp_curl)%cname             = 'socurl'
+      stypvar(jp_curl)%cunits            = 's-1'
+      stypvar(jp_curl)%rmissing_value    = 0.
+      stypvar(jp_curl)%valid_min         = -1000.
+      stypvar(jp_curl)%valid_max         =  1000.
+      stypvar(jp_curl)%clong_name        = 'Relative_Vorticity (curl)'
+      stypvar(jp_curl)%cshort_name       = 'socurl'
+      stypvar(jp_curl)%conline_operation = 'N/A'
+      stypvar(jp_curl)%caxis             = 'TYX'
+
+      ! Square of Relative Vorticity F point
+      ipk(jp_curl2)                       = 1   !2D
+      stypvar(jp_curl2)%cname             = 'socurl2'
+      stypvar(jp_curl2)%cunits            = 's-2'
+      stypvar(jp_curl2)%rmissing_value    = 0.
+      stypvar(jp_curl2)%valid_min         = -1000.
+      stypvar(jp_curl2)%valid_max         =  1000.
+      stypvar(jp_curl2)%clong_name        = 'Square of Relative_Vorticity (curl2)'
+      stypvar(jp_curl2)%cshort_name       = 'socurl2'
+      stypvar(jp_curl2)%conline_operation = 'N/A'
+      stypvar(jp_curl2)%caxis             = 'TYX'
+
+
+      ! Relative Vorticity zonal gradient V point
+      ipk(jp_dxcurl)                       = 1
+      stypvar(jp_dxcurl)%cname             = 'sodxcurl'
+      stypvar(jp_dxcurl)%cunits            = 'm-1*s-1'
+      stypvar(jp_dxcurl)%rmissing_value    = 0.
+      stypvar(jp_dxcurl)%valid_min         = -1000.
+      stypvar(jp_dxcurl)%valid_max         =  1000.
+      stypvar(jp_dxcurl)%clong_name        = 'Relative_Vorticity zonal gradient (dx_curl)'
+      stypvar(jp_dxcurl)%cshort_name       = 'sodxcurl'
+      stypvar(jp_dxcurl)%conline_operation = 'N/A'
+      stypvar(jp_dxcurl)%caxis             = 'TYX'
+
+      ! Relative Vorticity meridional gradient U point
+      ipk(jp_dycurl)                       = 1
+      stypvar(jp_dycurl)%cname             = 'sodycurl'
+      stypvar(jp_dycurl)%cunits            = 'm-1*s-1'
+      stypvar(jp_dycurl)%rmissing_value    = 0.
+      stypvar(jp_dycurl)%valid_min         = -1000.
+      stypvar(jp_dycurl)%valid_max         =  1000.
+      stypvar(jp_dycurl)%clong_name        = 'Relative Vorticity meridional gradient (dy_curl)'
+      stypvar(jp_dycurl)%cshort_name       = 'sodycurl'
+      stypvar(jp_dycurl)%conline_operation = 'N/A'
+      stypvar(jp_dycurl)%caxis             = 'TYX'
+
+      ! Square of Relative Vorticity zonal gradient V point
+      ipk(jp_dxcurl2)                       = 1
+      stypvar(jp_dxcurl2)%cname             = 'sodxcurl2'
+      stypvar(jp_dxcurl2)%cunits            = 'm-2*s-2'
+      stypvar(jp_dxcurl2)%rmissing_value    = 0.
+      stypvar(jp_dxcurl2)%valid_min         = -1000.
+      stypvar(jp_dxcurl2)%valid_max         =  1000.
+      stypvar(jp_dxcurl2)%clong_name        = 'Square Relative Vorticity zonal gradient (dx_curl2)'
+      stypvar(jp_dxcurl2)%cshort_name       = 'sodxcurl2'
+      stypvar(jp_dxcurl2)%conline_operation = 'N/A'
+      stypvar(jp_dxcurl2)%caxis             = 'TYX'
+
+      ! Square of Relative Vorticity meridional gradient U point
+      ipk(jp_dycurl2)                       = 1
+      stypvar(jp_dycurl2)%cname             = 'sodycurl2'
+      stypvar(jp_dycurl2)%cunits            = 'm-2*s-2'
+      stypvar(jp_dycurl2)%rmissing_value    = 0.
+      stypvar(jp_dycurl2)%valid_min         = -1000.
+      stypvar(jp_dycurl2)%valid_max         =  1000.
+      stypvar(jp_dycurl2)%clong_name        = 'Square of Relative Vorticity meridional gradient (dy_curl2)'
+      stypvar(jp_dycurl2)%cshort_name       = 'sodycurl2'
+      stypvar(jp_dycurl2)%conline_operation = 'N/A'
+      stypvar(jp_dycurl2)%caxis             = 'TYX'
+
+      ! Square of Zonal Velocity V point
+      ipk(jp_u2)                       = 1
+      stypvar(jp_u2)%cname             = 'vozocrtx2'
+      stypvar(jp_u2)%cunits            = 'm^2/s^2'
+      stypvar(jp_u2)%rmissing_value    = 0.
+      stypvar(jp_u2)%valid_min         = -10.
+      stypvar(jp_u2)%valid_max         =  10.
+      stypvar(jp_u2)%clong_name        = 'Square Zonal Velocity (vozocrtx2)'
+      stypvar(jp_u2)%cshort_name       = 'vozocrtx2'
+      stypvar(jp_u2)%conline_operation = 'N/A'
+      stypvar(jp_u2)%caxis             = 'TYX'
+
+      ! Square of Zonal Velocity V point
+      ipk(jp_v2)                       = 1
+      stypvar(jp_v2)%cname             = 'vomecrty2'
+      stypvar(jp_v2)%cunits            = 'm^2/s^2'
+      stypvar(jp_v2)%rmissing_value    = 0.
+      stypvar(jp_v2)%valid_min         = -10.
+      stypvar(jp_v2)%valid_max         =  10.
+      stypvar(jp_v2)%clong_name        = 'Square Meridional Velocity (vomecrty2)'
+      stypvar(jp_v2)%cshort_name       = 'vomecrty2'
+      stypvar(jp_v2)%conline_operation = 'N/A'
+      stypvar(jp_v2)%caxis             = 'TYX'
+
+      ! use zun and zvn to store f latitude and longitude for output
+      zun = getvar(cn_fhgr, cn_glamf, 1, npiglo, npjglo)
+      zvn = getvar(cn_fhgr, cn_gphif, 1, npiglo, npjglo)
+
+      ! look for  E-W periodicity
+      IF ( zun(1,1) == zun(npiglo-1,1) ) lperio = .TRUE.
+
+      ! create output fileset
+      ncout = create      (cf_out, cf_ufil, npiglo,  npjglo, 0)
+      ierr  = createvar   (ncout , stypvar, jp_nvar, ipk,    id_varout)
+      ierr  = putheadervar(ncout,  cf_ufil, npiglo,  npjglo, 0, pnavlon=zun, pnavlat=zvn )
+
+      tim  = getvar1d(cf_ufil, cn_vtimec, npt      )
+      ierr = putvar1d(ncout,   tim,       npt,  'T')
+
+   END SUBROUTINE CreateOutputFile
+END PROGRAM cdfeddyscale_pass1
diff --git a/src/cdfeke.f90 b/src/cdfeke.f90
new file mode 100644
index 0000000..c5b9350
--- /dev/null
+++ b/src/cdfeke.f90
@@ -0,0 +1,284 @@
+PROGRAM cdfeke
+  !!======================================================================
+  !!                     ***  PROGRAM cdfeke   ***
+  !!=====================================================================
+  !!  ** Purpose : Compute Eddy Kinetic Energy 
+  !!
+  !!  ** Method  : Use gridU gridU2, gridV gridV2 files produced by
+  !!               cdfmoy. Velocities are interpolated both on T points
+  !!               and the variance is computed. If -mke option is used
+  !!               the program also outputs MKE field
+  !!
+  !! History : pre  : 11/2004  : J.M. Molines : Original code
+  !!           2.1  : 04/2005  : J.M. Molines : use modules
+  !!           3.0  : 12/2010  : J.M. Molines : Doctor norm + Lic.
+  !!----------------------------------------------------------------------
+  USE cdfio 
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id$
+  !! Copyright (c) 2010, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)                            :: ji, jj, jk, jt      ! dummy loop index
+  INTEGER(KIND=4)                            :: narg, iargc         ! command line browsing
+  INTEGER(KIND=4)                            :: ijarg, ixtra, nfree ! command line browsing
+  INTEGER(KIND=4)                            :: npiglo, npjglo      ! size of the domain (horiz)
+  INTEGER(KIND=4)                            :: npk, npt            ! size of the domain vert and time
+  INTEGER(KIND=4)                            :: ncout               ! ncid of output file
+  INTEGER(KIND=4)                            :: ierr                ! Error status
+  INTEGER(KIND=4)                            :: ivar                ! variable counter
+  INTEGER(KIND=4)                            :: ip_eke, ip_mke      ! variable index
+  INTEGER(KIND=4), DIMENSION(2)              :: ipk, id_varout      ! 
+
+  REAL(KIND=4)                               :: ua, va              ! working arrays
+  REAL(KIND=4), DIMENSION(:),    ALLOCATABLE :: tim                 ! time variable
+  REAL(KIND=4), DIMENSION (:,:), ALLOCATABLE :: uc, vc, u2, v2      ! velocities etc...
+  REAL(KIND=4), DIMENSION (:,:), ALLOCATABLE :: eke                 ! velocities etc...
+  REAL(KIND=4), DIMENSION (:,:), ALLOCATABLE :: rmke                ! Mean Kinetic energy
+
+  CHARACTER(LEN=256)                         :: cf_out='eke.nc'     ! file name
+  CHARACTER(LEN=256)                         :: cf_ufil, cf_u2fil   ! file name
+  CHARACTER(LEN=256)                         :: cf_vfil, cf_v2fil   !   "
+  CHARACTER(LEN=256)                         :: cf_tfil             !   "
+  CHARACTER(LEN=256)                         :: cdum                ! dummy character variable
+
+  TYPE(variable), DIMENSION(2)               :: stypvar             !
+
+  LOGICAL                                    :: lchk                ! checking files existence
+  LOGICAL                                    :: lperio=.FALSE.      ! checking E-W periodicity
+  LOGICAL                                    :: leke=.TRUE.         ! compute EKE
+  LOGICAL                                    :: lmke=.FALSE.        ! compute MKE
+  LOGICAL                                    :: lnc4=.FALSE.        ! netcdf4 output (cunking and deflation)
+  !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  !!  Read command line
+  narg= iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage : cdfeke U-file [U2-file]  V-file [V2-file] T-file [-mke ] [-nc4] ...'
+     PRINT *,'            ... [-o output_file]'
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'        Compute the Eddy Kinetic Energy from previously computed'
+     PRINT *,'        mean values and mean squared values of velocity components.'
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS : both ''General Use'' or ''Reduced Use'' are acceptable'
+     PRINT *,'      * General Use: 5 files are given in argument, and EKE is computed'
+     PRINT *,'       U-file  : gridU type file with mean U component.' 
+     PRINT *,'       U2-file : gridU2 type file with mean U2 component.' 
+     PRINT *,'       V-file  : gridV type file with mean V component.' 
+     PRINT *,'       V2-file : gridV2 type file with mean V2 component.' 
+     PRINT *,'       T-file  : any gridT or gridT2 (smaller) file, used for EKE header.'
+     PRINT *,'       '
+     PRINT *,'      * Reduced Use: no U2/V2 file, only MKE is computed from U and V file.'
+     PRINT *,'       U-file  : gridU type file with mean U component.' 
+     PRINT *,'       V-file  : gridV type file with mean V component.' 
+     PRINT *,'       T-file  : any gridT or gridT2 (smaller) file, used for MKE header.'
+     PRINT *,'             '
+     PRINT *,'     OPTION :'
+     PRINT *,'       -mke  : output MKE field together with EKE. '
+     PRINT *,'       -nc4  : allow netcdf4 output with compression and chunking.'
+     PRINT *,'       -o output file : specify output file name instead of ', TRIM(cf_out)
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'        none'
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file : ', TRIM(cf_out) , ' unless -o option in use.'
+     PRINT *,'         variables : voeke (m2/s)'
+     PRINT *,'         variables : vomke (m2/s) if required'
+     STOP
+  ENDIF
+  !!
+  !! Initialisation from 1st file (all file are assume to have the same geometry)
+  cf_u2fil='none'
+  cf_v2fil='none'
+  ip_eke=0
+  ip_mke=0
+  ijarg = 1 ; ixtra = 0
+
+  ! read arguments in 2 step (1) determine the number of 'free' arguments : 3 or 5
+  !                          (2) according to the number of free arguments, set file names
+  ! ( 1 ) 
+  DO WHILE ( ijarg <= narg )
+     CALL getarg(ijarg, cdum ) ; ijarg = ijarg + 1
+     SELECT CASE ( cdum )
+     CASE ( '-mke' )
+         lmke = .true.
+     CASE ( '-nc4' )
+         lnc4 = .true.
+     CASE ( '-o'   )
+         CALL getarg( ijarg, cf_out) ; ijarg = ijarg + 1
+     CASE DEFAULT
+       ! count xtra arguments ( ie those without key )
+       ixtra = ixtra + 1
+     END SELECT
+  ENDDO
+  nfree = ixtra
+  ijarg = 1 ; ixtra = 0  ! reset ijarg for second step
+
+  IF ( nfree /= 3 .AND. nfree /= 5 ) THEN
+    PRINT *, ' +++ ERROR : not the correct number of free arguments'
+    PRINT *, '            Likely a wrong option or missing file name'
+    STOP
+  ENDIF
+
+  ! ( 2 )
+  DO WHILE ( ijarg <= narg )
+     CALL getarg(ijarg, cdum ) ; ijarg = ijarg + 1
+     SELECT CASE ( cdum )
+     CASE ( '-mke' )
+     CASE ( '-nc4' )
+     CASE ( '-o'   )
+         ijarg = ijarg + 1
+     CASE DEFAULT
+       ixtra = ixtra + 1 
+       SELECT CASE ( nfree )
+       CASE ( 3 )
+          IF ( ixtra == 1 ) cf_ufil = cdum
+          IF ( ixtra == 2 ) cf_vfil = cdum
+          IF ( ixtra == 3 ) cf_tfil = cdum
+          lmke = .true.
+          leke = .false.
+       CASE ( 5 )
+          IF ( ixtra == 1 ) cf_ufil  = cdum
+          IF ( ixtra == 2 ) cf_u2fil = cdum
+          IF ( ixtra == 3 ) cf_vfil  = cdum
+          IF ( ixtra == 4 ) cf_v2fil = cdum
+          IF ( ixtra == 5 ) cf_tfil  = cdum
+       END SELECT
+     END SELECT
+  ENDDO
+
+  lchk =           chkfile (cf_ufil )
+  lchk = lchk .OR. chkfile (cf_vfil )
+  lchk = lchk .OR. chkfile (cf_tfil )
+  IF (  leke ) THEN
+    lchk = lchk .OR. chkfile (cf_u2fil)
+    lchk = lchk .OR. chkfile (cf_v2fil)
+  ENDIF
+
+  IF ( lchk ) STOP ! missing files
+
+  npiglo = getdim (cf_ufil,cn_x)
+  npjglo = getdim (cf_ufil,cn_y)
+  npk    = getdim (cf_ufil,cn_z)
+  npt    = getdim (cf_ufil,cn_t)
+
+  IF ( npk == 0 ) npk=1 ! assume 1 level at least
+
+  stypvar(1)%ichunk = (/ npiglo, MAX(1, npjglo/30), 1, 1 /) 
+  stypvar(2)%ichunk = (/ npiglo, MAX(1, npjglo/30), 1, 1 /) 
+  
+  ivar = 1
+  IF ( leke ) THEN 
+    ip_eke=ivar
+    ipk(ip_eke)                       = npk
+    stypvar(ip_eke)%cname             = 'voeke'
+    stypvar(ip_eke)%cunits            = 'm2/s2'
+    stypvar(ip_eke)%rmissing_value    = 0.
+    stypvar(ip_eke)%valid_min         = 0.
+    stypvar(ip_eke)%valid_max         = 10000.
+    stypvar(ip_eke)%clong_name        = 'Eddy_Kinetic_Energy'
+    stypvar(ip_eke)%cshort_name       = 'voeke'
+    stypvar(ip_eke)%conline_operation = 'N/A'
+    stypvar(ip_eke)%caxis             = 'TZYX'
+    ivar = ivar + 1
+  ENDIF
+
+  IF ( lmke ) THEN
+    ip_mke=ivar
+    ipk(ip_mke)                       = npk
+    stypvar(ip_mke)%cname             = 'vomke'
+    stypvar(ip_mke)%cunits            = 'm2/s2'
+    stypvar(ip_mke)%rmissing_value    = 0.
+    stypvar(ip_mke)%valid_min         = 0.
+    stypvar(ip_mke)%valid_max         = 10000.
+    stypvar(ip_mke)%clong_name        = 'Mean_Kinetic_Energy'
+    stypvar(ip_mke)%cshort_name       = 'vomke'
+    stypvar(ip_mke)%conline_operation = 'N/A'
+    stypvar(ip_mke)%caxis             = 'TZYX'
+  ENDIF
+
+  ivar = MAX( ip_mke, ip_eke) ! set ivar to the effective number of variables to be output
+
+  PRINT *, 'npiglo = ', npiglo
+  PRINT *, 'npjglo = ', npjglo
+  PRINT *, 'npk    = ', npk
+  PRINT *, 'npt    = ', npt
+
+  ALLOCATE( uc(npiglo,npjglo), vc(npiglo,npjglo) )
+  ALLOCATE( tim(npt) )
+
+  IF ( leke ) THEN
+    ALLOCATE( eke(npiglo,npjglo)  )
+    ALLOCATE( u2(npiglo,npjglo), v2(npiglo,npjglo) )
+    eke(:,:) = 0.e0
+  ENDIF
+  IF (lmke ) THEN
+    ALLOCATE( rmke(npiglo,npjglo)  )
+    rmke(:,:) = 0.e0
+  ENDIF
+
+  ncout = create      (cf_out, cf_tfil, npiglo, npjglo, npk       , ld_nc4=lnc4 )
+  ierr  = createvar   (ncout,  stypvar, ivar,   ipk,    id_varout , ld_nc4=lnc4 )
+  ierr  = putheadervar(ncout,  cf_tfil, npiglo, npjglo, npk                     )
+
+  ! check for E_W periodicity
+  uc(:,:) = getvar(cf_tfil, cn_vlon2d, 1, npiglo, npjglo )
+  IF ( uc(1,1) ==  uc(npiglo-1,1) ) THEN 
+     lperio = .TRUE. 
+     PRINT *,' E-W periodicity detected '
+  ENDIF
+
+  DO jt = 1, npt  ! input file is likely to contain only one time frame but who knows ...
+    DO jk = 1, npk
+      uc(:,:) = getvar(cf_ufil,  cn_vozocrtx,               jk, npiglo, npjglo, ktime=jt )
+      vc(:,:) = getvar(cf_vfil,  cn_vomecrty,               jk, npiglo, npjglo, ktime=jt )
+      IF ( leke ) THEN
+        u2(:,:) = getvar(cf_u2fil, TRIM(cn_vozocrtx)//'_sqd', jk ,npiglo, npjglo, ktime=jt )
+        v2(:,:) = getvar(cf_v2fil, TRIM(cn_vomecrty)//'_sqd', jk ,npiglo, npjglo, ktime=jt )
+      ENDIF
+
+      ua = 0. ; va = 0. ; eke(:,:) = 0.
+      IF ( leke ) THEN
+        DO ji=2, npiglo
+          DO jj=2,npjglo
+              ua = 0.5* ((u2(ji,jj)-uc(ji,jj)*uc(ji,jj))+ (u2(ji-1,jj)-uc(ji-1,jj)*uc(ji-1,jj)))
+              va = 0.5* ((v2(ji,jj)-vc(ji,jj)*vc(ji,jj))+ (v2(ji,jj-1)-vc(ji,jj-1)*vc(ji,jj-1)))
+              eke(ji,jj) = 0.5 * ( ua + va )
+          END DO
+        END DO
+      ENDIF
+
+      IF ( lmke ) THEN
+        DO ji=2, npiglo
+          DO jj=2,npjglo
+              rmke(ji,jj)=  0.5* (0.5*( uc(ji,jj)*uc(ji,jj) + uc(ji-1,jj)*uc(ji-1,jj)) + &
+              &                   0.5*( vc(ji,jj)*vc(ji,jj) + vc(ji,jj-1)*vc(ji,jj-1)) )
+          END DO
+        END DO
+      ENDIF
+
+      IF ( lperio ) eke(1,:) = eke(npiglo-1,:)
+      IF ( leke ) THEN 
+         IF ( lperio ) eke(1,:) = eke(npiglo-1,:)
+         ierr=putvar(ncout,id_varout(ip_eke), eke,  jk ,npiglo, npjglo, ktime=jt )
+      ENDIF
+      IF ( lmke ) THEN 
+         IF ( lperio ) rmke(1,:) = rmke(npiglo-1,:)
+         ierr=putvar(ncout,id_varout(ip_mke), rmke, jk ,npiglo, npjglo, ktime=jt )
+      ENDIF
+    END DO
+  END DO ! time loop
+
+  tim  = getvar1d(cf_ufil, cn_vtimec, npt     )
+  ierr = putvar1d(ncout,   tim,       npt, 'T')
+
+  ierr = closeout(ncout)
+
+END PROGRAM cdfeke
diff --git a/cdfmoyt.f90 b/src/cdfenstat.f90
similarity index 52%
copy from cdfmoyt.f90
copy to src/cdfenstat.f90
index 36d94a7..77bc702 100644
--- a/cdfmoyt.f90
+++ b/src/cdfenstat.f90
@@ -1,39 +1,34 @@
-PROGRAM cdfmoyt
+PROGRAM cdfenstat
   !!======================================================================
-  !!                     ***  PROGRAM  cdfmoyt  ***
+  !!                     ***  PROGRAM  cdfenstat  ***
   !!=====================================================================
-  !!  ** Purpose : Compute mean values for all the variables in a bunch
-  !!               of cdf files given as arguments.
-  !!               Store the results on a 'similar' cdf file. This version
-  !!               differ from cdfmoy, because if the input files have many
-  !!               time frames in it, the output file will have the same 
-  !!               number of time frames, each being the average accross the
-  !!               input files.
+  !!  ** Purpose : Compute mean values standard dev for all the variables 
+  !!               in a bunch of cdf files given as arguments (ensemble)
+  !!               Store the results on a 'similar' cdf file (same number
+  !!               of time frame) with same variables + stdev_variable
   !!
-  !!  ** Method  : Also store the mean squared values for the nn_sqdvar
+  !!  ** Method  : Use optimize algorithm for better accuracy
   !!               variables belonging to cn_sqdvar(:), than can be changed 
   !!               in the nam_cdf_names namelist if wished.
   !!
-  !! History : 2.0  : 11/2004  : J.M. Molines : Original code
-  !!         : 2.1  : 06/2007  : P. Mathiot   : Modif for forcing fields
-  !!           3.0  : 12/2010  : J.M. Molines : Doctor norm + Lic.
+  !!  ** Reference : Accuracy of floating point arithmetic.
+  !!
+  !! History  3.0  : 07/2015  : J.M. Molines : from cdfmoyt
   !!----------------------------------------------------------------------
   !!----------------------------------------------------------------------
   !!   routines      : description
-  !!   varchk2       : check if variable is candidate for square mean
   !!----------------------------------------------------------------------
   USE cdfio 
   USE modcdfnames
   !!----------------------------------------------------------------------
   !! CDFTOOLS_3.0 , MEOM 2011
-  !! $Id$
+  !! $Id: cdfenstat.f90 550 2011-09-19 16:07:45Z molines $
   !! Copyright (c) 2010, J.-M. Molines
   !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
   !!-----------------------------------------------------------------------------
   IMPLICIT NONE
 
-  INTEGER(KIND=4)                               :: jk, jfil, jrec     ! dummy loop index
-  INTEGER(KIND=4)                               :: jvar, jv, jt       ! dummy loop index
+  INTEGER(KIND=4)                               :: jk, jfil, jrec, jv! dummy loop index
   INTEGER(KIND=4)                               :: ierr               ! working integer
   INTEGER(KIND=4)                               :: inpt               ! working integer
   INTEGER(KIND=4)                               :: narg, iargc, ijarg ! browsing command line
@@ -41,39 +36,42 @@ PROGRAM cdfmoyt
   INTEGER(KIND=4)                               :: npiglo, npjglo     ! size of the domain
   INTEGER(KIND=4)                               :: npk, npt           ! size of the domain
   INTEGER(KIND=4)                               :: nvars              ! number of variables in a file
-  INTEGER(KIND=4)                               :: ntframe            ! cumul of time frame
-  INTEGER(KIND=4)                               :: ncout, ncout2      ! ncid of output files
+  INTEGER(KIND=4)                               :: ncout              ! ncid of output files
   INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_var             ! arrays of var id's
   INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: ipk                ! arrays of vertical level for each var
   INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_varout          ! varid's of average vars
-  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_varout2         ! varid's of sqd average vars
 
-  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: v2d                ! array to read a layer of data
+  REAL(KIND=4), DIMENSION(:,:,:),   ALLOCATABLE :: v3d                ! array to read a layer of data for all files
+  REAL(KIND=4), DIMENSION(:,:,:,:), ALLOCATABLE :: v4d                ! array to read a layer of data for all files
   REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: tim                ! time counter
   REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: zspval_in          ! input missing value
 
-  REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: dtab, dtab2        ! arrays for cumulated values
+  REAL(KIND=8), DIMENSION(:,:,:),     ALLOCATABLE :: dtabn, dtab2n      ! arrays for cumulated values
+  REAL(KIND=8), DIMENSION(:,:,:),     ALLOCATABLE :: dtabb, dtab2b      ! arrays for cumulated values
+  REAL(KIND=8), DIMENSION(:,:,:),     ALLOCATABLE :: dtmp               ! temporary array
+  REAL(KIND=8), DIMENSION(:,:,:,:),   ALLOCATABLE :: d4tabn, d4tab2n    ! arrays for cumulated values
+  REAL(KIND=8), DIMENSION(:,:,:,:),   ALLOCATABLE :: d4tabb, d4tab2b    ! arrays for cumulated values
+  REAL(KIND=8), DIMENSION(:,:,:,:),   ALLOCATABLE :: d4tmp               ! temporary array
   REAL(KIND=8), DIMENSION(:),       ALLOCATABLE :: dtotal_time        ! to compute mean time
 
   CHARACTER(LEN=256)                            :: cf_in              ! input file names
   CHARACTER(LEN=256)                            :: cf_out  = 'cdfmoy.nc'  ! output file for average
-  CHARACTER(LEN=256)                            :: cf_out2 = 'cdfmoy2.nc' ! output file for squared average
   CHARACTER(LEN=256)                            :: cv_dep             ! depth dimension name
   CHARACTER(LEN=256)                            :: cldum              ! dummy string argument
   CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cf_list            ! list of input files
   CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_nam             ! array of var name
-  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_nam2            ! array of var2 name for output
 
   TYPE (variable), DIMENSION(:),    ALLOCATABLE :: stypvar            ! attributes for average values
-  TYPE (variable), DIMENSION(:),    ALLOCATABLE :: stypvar2           ! attributes for square averaged values
 
   LOGICAL                                       :: lspval0 = .FALSE.  ! cdfmoy_chsp flag
+  LOGICAL                                       :: lnc4    = .FALSE.  ! flag for netcdf4 chinking and deflation
+  LOGICAL                                       :: lv4d    = .FALSE.  ! flag for netcdf4 chinking and deflation
   !!----------------------------------------------------------------------------
   CALL ReadCdfNames()
 
   narg= iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfmoyt list_of_model_files [-spval0]  '
+     PRINT *,' usage : cdfenstat list_of_model_files [-spval0] [-nc4] [-v4d] -o OUT-file]'
      PRINT *,'     PURPOSE :'
      PRINT *,'       Compute the time average of a list of files given as arguments.' 
      PRINT *,'       This program handle multi time-frame files is such a way that'
@@ -101,14 +99,17 @@ PROGRAM cdfmoyt
      PRINT *,'               variables and take care of the input missing_value.'
      PRINT *,'               This option is usefull if missing_values differ from files '
      PRINT *,'               to files; it was formely done by cdfmoy_chsp).'
+     PRINT *,'       [ -nc4 ] : output file will be in netcdf4, with chunking and deflation'
+     PRINT *,'       [ -v4d ] : uses 4D arrays for improved performance (use more memory !)'
+     PRINT *,'       [ -o OUT-file ] : specify a name for output file instead of '//TRIM(cf_out)
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'       none '
      PRINT *,'      '
      PRINT *,'     OUTPUT : '
-     PRINT *,'       netcdf file : ', TRIM(cf_out),' and ',TRIM(cf_out2)
-     PRINT *,'       variables : are the same than in the input files. For squared averages' 
-     PRINT *,'       _sqd is append to the original variable name.'
+     PRINT *,'       netcdf file : ', TRIM(cf_out), 'unless -o option in use'
+     PRINT *,'       variables : are the same than in the input files. Standard Dev are '
+     PRINT *,'        named  stdev_<variable>'
      STOP
   ENDIF
 
@@ -121,6 +122,12 @@ PROGRAM cdfmoyt
      SELECT CASE ( cldum )
      CASE ( '-spval0' )   ! option to reset spval to 0 in the output files
         lspval0 = .TRUE.
+     CASE ( '-nc4   ' )   ! option to reset spval to 0 in the output files
+        lnc4 = .TRUE.
+     CASE ( '-v4d  '  )   ! option to reset spval to 0 in the output files
+        lv4d = .TRUE.
+     CASE ( '-o   ' )   ! option to reset spval to 0 in the output files
+        CALL getarg (ijarg, cf_out) ; ijarg = ijarg + 1
      CASE DEFAULT         ! then the argument is a file
         nfil          = nfil + 1
         cf_list(nfil) = TRIM(cldum)
@@ -129,7 +136,6 @@ PROGRAM cdfmoyt
   ! Initialisation from  1rst file (all file are assume to have the same geometry)
   ! time counter can be different for each file in the list. It is read in the
   ! loop for files
-
   IF ( chkfile (cf_list(1)) ) STOP ! missing file
 
   cf_in  = cf_list(1)
@@ -172,62 +178,66 @@ PROGRAM cdfmoyt
   PRINT *, 'npk    = ', npk
   PRINT *, 'npt    = ', npt
 
-  ALLOCATE( dtab(npiglo,npjglo), dtab2(npiglo,npjglo), v2d(npiglo,npjglo) )
+  IF ( .NOT. lv4d ) THEN 
+  ALLOCATE( v3d(npiglo,npjglo,npt) )
+  ALLOCATE( dtabn(npiglo,npjglo,npt), dtab2n(npiglo,npjglo,npt)) 
+  ALLOCATE( dtabb(npiglo,npjglo,npt), dtab2b(npiglo,npjglo,npt), dtmp(npiglo,npjglo,npt))
+  ENDIF
+
   ALLOCATE( dtotal_time(npt), tim(npt) )
 
   nvars = getnvar(cf_in)
   PRINT *,' nvars = ', nvars
 
-  ALLOCATE (cv_nam(nvars), cv_nam2(nvars) )
-  ALLOCATE (stypvar(nvars), stypvar2(nvars) )
-  ALLOCATE (id_var(nvars), ipk(nvars), id_varout(nvars), id_varout2(nvars)  )
+  ALLOCATE (cv_nam(2*nvars) )
+  ALLOCATE (stypvar(2*nvars))
+  ALLOCATE (id_var(2*nvars), ipk(2*nvars), id_varout(2*nvars)  )
 
   ! get list of variable names and collect attributes in stypvar (optional)
-  cv_nam(:) = getvarname(cf_in,nvars, stypvar)
+  cv_nam(1:nvars) = getvarname(cf_in,nvars, stypvar)
+  DO jv =1, nvars
+    cv_nam(jv+nvars) ='stdev_'//TRIM(cv_nam(jv))
+  ENDDO
+  ! choose chunk size for output ... not easy not used if lnc4=.false. but anyway ..
+  DO jv = 1, 2*nvars
+     stypvar(jv)%ichunk=(/npiglo,MAX(1,npjglo/30),1,1 /)
+  ENDDO
+
 
   IF ( lspval0 ) THEN 
      ALLOCATE ( zspval_in(nvars) )
-     zspval_in(:) = stypvar(:)%rmissing_value
+     zspval_in(:) = stypvar(1:nvars)%rmissing_value
      stypvar(:)%rmissing_value = 0.
   ENDIF
 
-  DO jvar = 1, nvars
+  DO jv = 1, nvars
      ! variables that will not be computed or stored are named 'none'
-     IF ( varchk2 ( cv_nam(jvar) ) ) THEN 
-        cv_nam2(jvar)                    = TRIM(cv_nam(jvar))//'_sqd'
-        stypvar2(jvar)%cname             = TRIM(stypvar(jvar)%cname)//'_sqd'         ! name
-        stypvar2(jvar)%cunits            = '('//TRIM(stypvar(jvar)%cunits)//')^2'    ! unit
-        stypvar2(jvar)%rmissing_value    = stypvar(jvar)%rmissing_value              ! missing_value
-        stypvar2(jvar)%valid_min         = 0.                                        ! valid_min = zero
-        stypvar2(jvar)%valid_max         = stypvar(jvar)%valid_max**2                ! valid_max *valid_max
-        stypvar2(jvar)%scale_factor      = 1.
-        stypvar2(jvar)%add_offset        = 0.
-        stypvar2(jvar)%savelog10         = 0.
-        stypvar2(jvar)%clong_name        = TRIM(stypvar(jvar)%clong_name)//'_Squared'   ! 
-        stypvar2(jvar)%cshort_name       = TRIM(stypvar(jvar)%cshort_name)//'_sqd'     !
-        stypvar2(jvar)%conline_operation = TRIM(stypvar(jvar)%conline_operation) 
-        stypvar2(jvar)%caxis             = TRIM(stypvar(jvar)%caxis) 
-     ELSE
-        cv_nam2(jvar) = 'none'
-     END IF
+        stypvar(jv+nvars)%cname             = cv_nam(jv+nvars)
+        stypvar(jv+nvars)%cunits            = TRIM(stypvar(jv)%cunits)             ! unit
+        stypvar(jv+nvars)%rmissing_value    = stypvar(jv)%rmissing_value           ! missing_value
+        stypvar(jv+nvars)%valid_min         = 0.                                   ! valid_min = zero
+        stypvar(jv+nvars)%valid_max         = stypvar(jv)%valid_max                ! valid_max *valid_max
+        stypvar(jv+nvars)%scale_factor      = 1.
+        stypvar(jv+nvars)%add_offset        = 0.
+        stypvar(jv+nvars)%savelog10         = 0.
+        stypvar(jv+nvars)%clong_name        = TRIM(stypvar(jv)%clong_name)//'_Std_Dev'   ! 
+        stypvar(jv+nvars)%cshort_name       = cv_nam(jv+nvars)
+        stypvar(jv+nvars)%conline_operation = TRIM(stypvar(jv)%conline_operation) 
+        stypvar(jv+nvars)%caxis             = TRIM(stypvar(jv)%caxis) 
   END DO
 
-  id_var(:)  = (/(jv, jv=1,nvars)/)
+  id_var(:)  = (/(jv, jv=1,2*nvars)/)
   ! ipk gives the number of level or 0 if not a T[Z]YX  variable
-  ipk(:)     = getipk (cf_in,nvars,cdep=cv_dep)
+  ipk(1:nvars)  = getipk (cf_in,nvars,cdep=cv_dep)
+  ipk(nvars+1:2*nvars) = ipk(1:nvars)
   WHERE( ipk == 0 ) cv_nam='none'
   stypvar( :)%cname = cv_nam
-  stypvar2(:)%cname = cv_nam2
 
   ! create output file taking the sizes in cf_in
-  ncout  = create      (cf_out,  cf_in,    npiglo, npjglo, npk, cdep=cv_dep)
-  ierr   = createvar   (ncout ,  stypvar,  nvars,  ipk,    id_varout       )
+  ncout  = create      (cf_out,  cf_in,     npiglo, npjglo, npk, cdep=cv_dep, ld_nc4=lnc4)
+  ierr   = createvar   (ncout ,  stypvar,  2*nvars,  ipk,   id_varout       , ld_nc4=lnc4)
   ierr   = putheadervar(ncout,   cf_in,    npiglo, npjglo, npk, cdep=cv_dep)
 
-  ncout2 = create      (cf_out2, cf_in,    npiglo, npjglo, npk, cdep=cv_dep)
-  ierr   = createvar   (ncout2,  stypvar2, nvars,  ipk,    id_varout2      )
-  ierr   = putheadervar(ncout2,  cf_in,    npiglo, npjglo, npk, cdep=cv_dep)
-
   ! Compute the mean time for each mean frame
   dtotal_time(:) = 0.d0
   DO jfil = 1, nfil 
@@ -237,65 +247,76 @@ PROGRAM cdfmoyt
   END DO
   tim(:) = dtotal_time(:)/ nfil
   ierr   = putvar1d(ncout,  tim, npt, 'T')
-  ierr   = putvar1d(ncout2, tim, npt, 'T')
 
-  DO jrec = 1, npt
 
-     DO jvar = 1,nvars
-        IF ( cv_nam(jvar) == cn_vlon2d .OR. &     ! nav_lon
-             cv_nam(jvar) == cn_vlat2d ) THEN     ! nav_lat
+     DO jv = 1,nvars
+        IF ( cv_nam(jv) == cn_vlon2d .OR. &     ! nav_lon
+           & cv_nam(jv) == cn_vlat2d .OR. &
+           & cv_nam(jv) == 'none'    ) THEN     ! nav_lat
            ! skip these variable
         ELSE
-           PRINT *,' Working with ', TRIM(cv_nam(jvar)), ipk(jvar)
-           DO jk = 1, ipk(jvar)
-              PRINT *,'level ',jk
-              dtab(:,:) = 0.d0 ; dtab2(:,:) = 0.d0 
-              ntframe = 0
+           PRINT *,' Working with ', TRIM(cv_nam(jv)), ipk(jv)
+           IF ( lv4d) THEN
+             ALLOCATE( v4d(npiglo,npjglo,ipk(jv),npt) )
+             ALLOCATE( d4tabn(npiglo,npjglo,ipk(jv),npt), d4tab2n(npiglo,npjglo,ipk(jv),npt) ) 
+             ALLOCATE( d4tabb(npiglo,npjglo,ipk(jv),npt), d4tab2b(npiglo,npjglo,ipk(jv),npt), d4tmp(npiglo,npjglo,ipk(jv),npt))
+
               DO jfil = 1, nfil
                  cf_in     = cf_list(jfil)
-                 v2d(:,:)  = getvar(cf_in, cv_nam(jvar), jk, npiglo, npjglo, ktime=jrec )
-                 IF ( lspval0 )  WHERE (v2d == zspval_in(jvar))  v2d = 0.  ! change missing values to 0
-                 dtab(:,:) = dtab(:,:) + v2d(:,:)
-                 IF (cv_nam2(jvar) /= 'none' ) dtab2(:,:) = dtab2(:,:) + v2d(:,:)*v2d(:,:)
+                 v4d(:,:,:,:)  = getvar4d(cf_in, cv_nam(jv), npiglo, npjglo, ipk(jv), npt )
+                 IF ( jfil == 1 ) THEN
+                    d4tabb(:,:,:,:)=v4d(:,:,:,:) ; d4tab2b(:,:,:,:)=0.d0
+                    CYCLE
+                 ENDIF
+                 IF ( lspval0 )  WHERE ( v4d == zspval_in(jv) )  v4d = 0.  ! change missing values to 0
+                 d4tmp(:,:,:,:)   = v4d(:,:,:,:) - d4tabb(:,:,:,:)
+                 d4tabn(:,:,:,:)  = d4tabb(:,:,:,:)  + d4tmp(:,:,:,:) / jfil
+                 d4tab2n(:,:,:,:) = d4tab2b(:,:,:,:) + d4tmp(:,:,:,:) * ( v4d(:,:,:,:) - d4tabn(:,:,:,:) )
+                 ! swap tabs
+                 d4tabb(:,:,:,:)  = d4tabn(:,:,:,:)
+                 d4tab2b(:,:,:,:) = d4tab2n(:,:,:,:)
               END DO
 
               ! store variable on outputfile
-              ierr = putvar(ncout, id_varout(jvar), SNGL(dtab(:,:)/nfil), jk, npiglo, npjglo, kwght=nfil, ktime = jrec )
-              IF (cv_nam2(jvar) /= 'none' )  THEN 
-                 ierr = putvar(ncout2, id_varout2(jvar), SNGL(dtab2(:,:)/nfil), jk, npiglo, npjglo, kwght=nfil, ktime=jrec)
-              ENDIF
+              DO jrec = 1, npt
+                DO jk=1, ipk(jv)
+                ierr = putvar(ncout, id_varout(jv),       SNGL(d4tabn(:,:,jk,jrec)),                 jk, npiglo, npjglo, kwght=nfil, ktime = jrec )
+                ierr = putvar(ncout, id_varout(jv+nvars), SQRT(SNGL(d4tab2n(:,:,jk,jrec))/(nfil-1)), jk, npiglo, npjglo, kwght=nfil, ktime = jrec )
+                ENDDO
+              ENDDO
+
+             ! Deqllocate array for this variable
+             DEALLOCATE( v4d, d4tabn, d4tab2n, d4tabb, d4tab2b, d4tmp )
+           ELSE
+           DO jk = 1, ipk(jv)
+              PRINT *,'level ',jk
+              DO jfil = 1, nfil
+                 cf_in     = cf_list(jfil)
+                 v3d(:,:,:)  = getvar3dt(cf_in, cv_nam(jv), jk, npiglo, npjglo, npt )
+                 IF ( jfil == 1 ) THEN
+                    dtabb(:,:,:)=v3d(:,:,:) ; dtab2b(:,:,:)=0.d0
+                    CYCLE
+                 ENDIF
+                 IF ( lspval0 )  WHERE ( v3d == zspval_in(jv) )  v3d = 0.  ! change missing values to 0
+                 dtmp(:,:,:)   = v3d(:,:,:) - dtabb(:,:,:)
+                 dtabn(:,:,:)  = dtabb(:,:,:)  + dtmp(:,:,:) / jfil
+                 dtab2n(:,:,:) = dtab2b(:,:,:) + dtmp(:,:,:) * ( v3d(:,:,:) - dtabn(:,:,:) )
+                 ! swap tabs
+                 dtabb(:,:,:)  = dtabn(:,:,:)
+                 dtab2b(:,:,:) = dtab2n(:,:,:)
+              END DO
 
+              ! store variable on outputfile
+              DO jrec = 1, npt
+                ierr = putvar(ncout, id_varout(jv),       SNGL(dtabn(:,:,jrec)),                 jk, npiglo, npjglo, kwght=nfil, ktime = jrec )
+                ierr = putvar(ncout, id_varout(jv+nvars), SQRT(SNGL(dtab2n(:,:,jrec))/(nfil-1)), jk, npiglo, npjglo, kwght=nfil, ktime = jrec )
+              ENDDO
            END DO  ! loop to next level
+           ENDIF 
+
         END IF
      END DO ! loop to next var in file
-  END DO ! loop to next record in input file
 
   ierr = closeout(ncout)
-  ierr = closeout(ncout2)
-
-CONTAINS 
-
-  LOGICAL FUNCTION varchk2 ( cd_var ) 
-    !!---------------------------------------------------------------------
-    !!                  ***  FUNCTION varchk2  ***
-    !!
-    !! ** Purpose : Return true if cd_var is candidate for mean squared value  
-    !!
-    !! ** Method  : List of candidate is established in modcdfnames, and
-    !!              can be changed via the nam_cdf_names namelist   
-    !!----------------------------------------------------------------------
-    CHARACTER(LEN=*), INTENT(in) :: cd_var
-
-    INTEGER(KIND=4)              :: jv
-    !!----------------------------------------------------------------------
-    varchk2 = .FALSE.
-    DO jv = 1, nn_sqdvar 
-       IF ( cd_var == cn_sqdvar(jv) ) THEN
-          varchk2 = .TRUE.
-          EXIT
-       ENDIF
-    ENDDO
-
-  END FUNCTION varchk2
-
-END PROGRAM cdfmoyt
+
+END PROGRAM cdfenstat
diff --git a/cdfets.f90 b/src/cdfets.f90
similarity index 99%
rename from cdfets.f90
rename to src/cdfets.f90
index 1cb5e79..755fcb5 100644
--- a/cdfets.f90
+++ b/src/cdfets.f90
@@ -16,6 +16,8 @@ PROGRAM cdfets
   !!               (6) Output on netcdf file ets.nc :  
   !!                   ets = voets ;  rosby_radius = sorosrad
   !!
+  !!  ** Reference : Chelton et Al.  (1998)  J. Phys.Oceanogr. 28, 433-460
+  !!
   !!  ** Remarks : A special care has been taken with respect to land value 
   !!               which have been set to spval (-1000.) and not 0 as usual.
   !!               This is because a value of 0.00 has a physical meaning for N.
diff --git a/src/cdffindij.f90 b/src/cdffindij.f90
new file mode 100644
index 0000000..821724c
--- /dev/null
+++ b/src/cdffindij.f90
@@ -0,0 +1,159 @@
+PROGRAM cdffindij
+  !!======================================================================
+  !!                     ***  PROGRAM  cdffindij  ***
+  !!=====================================================================
+  !!  ** Purpose : Return the window index (imin imax jmin jmax )
+  !!               for the geographical windows given on input 
+  !!               (longmin longmax latmin matmax)
+  !!
+  !!  ** Method  : Read the coordinate/mesh_hgr file and look for the glam,
+  !!               gphi variables.
+  !!               Then use a search algorithm to find the corresponding I J
+  !!               The point type ( T U V F ) is specified on the command 
+  !!               line as well as the name of the coordinate/mesh hgr file.
+  !!
+  !! History : 2.1  : 11/2005  : J.M. Molines : Original code
+  !!           3.0  : 12/2010  : J.M. Molines : Doctor norm + Lic.
+  !!           3.0  : 02/2016  : J.M. Molines : add -f, -d, -o options
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE cdftools
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id$
+  !! Copyright (c) 2010, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)    :: ji                         ! dummy loop index
+  INTEGER(KIND=4)    :: narg, iargc                ! command line
+  INTEGER(KIND=4)    :: ijarg, ireq                ! command line
+  INTEGER(KIND=4)    :: iimin, iimax, ijmin, ijmax ! model grid window
+  INTEGER(KIND=4)    :: inum=10, iout=6            ! logical unit of assci files
+  INTEGER(KIND=4)    :: nfields                    ! number of fields in file_list
+  INTEGER(KIND=4)    :: ipx, ipy                   ! field number for X and Y in file_list
+
+  REAL(KIND=4)       :: xmin, xmax, ymin, ymax     ! geographical window
+  REAL(KIND=4)       :: zlon, zlat                 ! position of model point
+
+  CHARACTER(LEN=256) :: cltype='F'                 ! point type to search for
+  CHARACTER(LEN=256) :: cldum                      ! dummy character variable
+  CHARACTER(LEN=256) :: clcoo                      ! dummy character variable
+  CHARACTER(LEN=256) :: cf_list                    ! list_file name
+  CHARACTER(LEN=256) :: cf_out                     ! output file name
+  CHARACTER(LEN=256) :: cldes='XY'                 ! descriptor for input file
+  CHARACTER(LEN=50), DIMENSION(:), ALLOCATABLE  :: cfields ! string array to receive
+                                                   ! fields of the list_file
+
+  LOGICAL            :: l_file_in=.false.          ! flag for input file
+  LOGICAL            :: l_file_ou=.false.          ! flag for output file
+  LOGICAL            :: l_append =.false.          ! flag for appending x,y to existing data on line
+  LOGICAL            :: l_lonlat =.false.          ! flag for adding lon lat to the output
+  !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+  clcoo = cn_fcoo
+
+  !!  Read command line and output usage message if not compliant.
+  narg= iargc()
+  IF ( narg < 4 ) THEN
+     PRINT *,' usage :   cdffindij  xmin xmax ymin ymax  [-c COOR-file] [-p point_type]...'
+     PRINT *,'                    [-f list_file ] [-d decriptor] [-o output_file] [-a] [-l]'
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'       Return the model limit (i,j space) of the geographical window ' 
+     PRINT *,'       given on the input line. If using -f list_file option, then the output'
+     PRINT *,'       is just a single point, not a window, and xmin, xmax, ymin ymax are not'
+     PRINT *,'       used at all.'
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       xmin xmax ymin ymax : geographical limits of the window, in lon/lat' 
+     PRINT *,'       (relevant only if -f option not used.)'
+     PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'       [-c COOR-file ] : specify a particular coordinate file' 
+     PRINT *,'                     default is ',TRIM(cn_fcoo)
+     PRINT *,'       [-p point type] : specify the point on the C-grid (T U V F)'
+     PRINT *,'                     default is ',TRIM(cltype)
+     PRINT *,'       [-f list_file ] : list_file is an ascii file describing the location'
+     PRINT *,'                (one per line) of geographical points to be translated to '
+     PRINT *,'                model (i,j) point. Unless specified with -d option, this list'
+     PRINT *,'                file contains Longitude (X) Latitudes (Y) information.'
+     PRINT *,'       [-d descriptor] : descriptor is a string indicating the position of'
+     PRINT *,'                X and Y coordinates for the lines of list_file. Default value'
+     PRINT *,'                of the descriptor is ''XY''. Any other field on the line is '
+     PRINT *,'                indicated with any characterm except X or Y. Example of valid'
+     PRINT *,'                descriptor : ''oXYooo'' or ''ooYabcdfXooo'' '
+     PRINT *,'       [-a  ] : With this option, output is similar to input with I,J appended'
+     PRINT *,'                to the corresponding line.'
+     PRINT *,'       [-l  ] : With this option, also output the exact model longitude and '
+     PRINT *,'                latitude of the I,J point.'
+     PRINT *,'       [-o output_file] : write output in ascii output_file instead of standard'
+     PRINT *,'                output.'
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'       ', TRIM(cn_fcoo),' or the specified coordinates file.' 
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       Output is done on standard output.'
+     STOP
+  ENDIF
+
+  ijarg = 1 ; ireq = 0
+  DO WHILE ( ijarg <= narg ) 
+    CALL getarg(ijarg, cldum ) ; ijarg=ijarg+1
+    SELECT CASE ( cldum )
+    CASE ( '-c' ) ; CALL getarg(ijarg, clcoo  ) ; ijarg=ijarg+1
+    CASE ( '-p' ) ; CALL getarg(ijarg, cltype ) ; ijarg=ijarg+1
+    CASE ( '-f' ) ; CALL getarg(ijarg, cf_list) ; ijarg=ijarg+1 ;  l_file_in=.true.
+    CASE ( '-d' ) ; CALL getarg(ijarg, cldes  ) ; ijarg=ijarg+1
+    CASE ( '-o' ) ; CALL getarg(ijarg, cf_out ) ; ijarg=ijarg+1 ;  l_file_ou=.true.
+    CASE ( '-a' ) ;                                                l_append =.true.
+    CASE ( '-l' ) ;                                                l_lonlat =.true.
+    CASE DEFAULT
+       ireq=ireq+1
+       SELECT CASE (ireq)
+       CASE ( 1 ) ; READ(cldum,*) xmin
+       CASE ( 2 ) ; READ(cldum,*) xmax
+       CASE ( 3 ) ; READ(cldum,*) ymin
+       CASE ( 4 ) ; READ(cldum,*) ymax
+       CASE DEFAULT 
+         PRINT *,' Too many arguments !' ; STOP
+       END SELECT
+    END SELECT
+  END DO
+  IF ( l_file_in) THEN
+     ! interpret descriptor
+     nfields=LEN(TRIM(cldes) )
+     ipx=INDEX(TRIM(cldes),'X')
+     ipy=INDEX(TRIM(cldes),'Y')
+     ALLOCATE( cfields(nfields))
+     ! open list_file and loop over lines
+     OPEN(inum, FILE=cf_list)
+     IF ( l_file_ou ) OPEN(iout, FILE=cf_out)
+     DO 
+       READ(inum,*,END=999) cfields
+       READ(cfields(ipx),*) xmin
+       READ(cfields(ipy),*) ymin
+       CALL cdf_findij ( xmin, xmin, ymin, ymin, iimin, iimax, ijmin, ijmax, cd_coord=clcoo, & 
+           &cd_point=cltype, cd_verbose='n', plonmin=zlon, platmin=zlat)
+       IF ( l_append ) THEN
+         DO ji = 1, nfields
+           WRITE(iout,'(a,x)',advance="no") TRIM(cfields(ji))
+         ENDDO
+       ENDIF
+       IF ( l_lonlat ) THEN
+           WRITE(iout,'(g20.9,x)',advance="no")  zlon
+           WRITE(iout,'(g20.9,x)',advance="no")  zlat
+       ENDIF
+         WRITE(iout,'(i10,x)',advance="no") iimin
+         WRITE(iout,'(i10,x)'             ) ijmin
+     ENDDO
+ 999 CONTINUE
+
+  ELSE
+    CALL cdf_findij ( xmin, xmax, ymin, ymax, iimin, iimax, ijmin, ijmax, cd_coord=clcoo, cd_point=cltype, cd_verbose='y')
+  ENDIF
+
+END PROGRAM cdffindij
diff --git a/cdffixtime.f90 b/src/cdffixtime.f90
similarity index 100%
rename from cdffixtime.f90
rename to src/cdffixtime.f90
diff --git a/cdfflxconv.f90 b/src/cdfflxconv.f90
similarity index 100%
rename from cdfflxconv.f90
rename to src/cdfflxconv.f90
diff --git a/cdffracinv.f90 b/src/cdffracinv.f90
similarity index 100%
rename from cdffracinv.f90
rename to src/cdffracinv.f90
diff --git a/src/cdffwc.f90 b/src/cdffwc.f90
new file mode 100644
index 0000000..640ec69
--- /dev/null
+++ b/src/cdffwc.f90
@@ -0,0 +1,319 @@
+PROGRAM cdffwc
+  !!======================================================================
+  !!                      ***  PROGRAM  cdffwc   ***
+  !!=====================================================================
+  !!  ** Purpose : Computes the freshwater content in a given basin from top
+  !!               to bottom for each layer. Can handle full step configuration
+  !!               using the -full option.'
+  !!
+  !!  ** Method  : compute fwc = sum(e1*e2*e3) - sum(S*e1*e2*e3)/Sref * btmask
+  !!                 with reference salinity Sref (=34.7) and 
+  !!                 the sub-basin mask btmask
+  !!
+  !!               based on cdfvertmean routine
+  !!
+  !! History : 0.1  : 09/2016  : M. Scheinert : First adaption
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE modcdfnames
+  USE modutils
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2016
+  !! $Id$
+  !! Copyright (c) 2016, J.-M. Molines & Markus Scheinert (GEOMAR)
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+   INTEGER(KIND=4)                            :: jk, jvar, jvarin, jt ! dummy loop index
+   INTEGER(KIND=4)                            :: ierr, ij, iko        ! working integer
+   INTEGER(KIND=4)                            :: narg, iargc, ijarg   ! command line 
+   INTEGER(KIND=4)                            :: npiglo, npjglo       ! size of the domain
+   INTEGER(KIND=4)                            :: npk, npt             ! size of the domain
+   INTEGER(KIND=4)                            :: nvars, ivar          ! variables in input
+   INTEGER(KIND=4)                            :: nvaro=1              ! variables for output
+   INTEGER(KIND=4), DIMENSION(:), ALLOCATABLE :: ipk, id_varout       ! levels and varid's of output vars
+   INTEGER(KIND=4)                            :: ncout 
+
+   REAL(KIND=4), PARAMETER                    :: pprho0 = 1020.       ! water density (kg/m3)
+   REAL(KIND=4), PARAMETER                    :: ppcp   = 4000.       ! calorific capacity (J/kg/m3)
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE  :: e3t,area,ssh         ! vertical metric
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE  :: zt                   ! working input variable
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE  :: tmask                ! npiglo x npjglo
+   REAL(KIND=4), DIMENSION(:),   ALLOCATABLE  :: tim                  ! time counter
+   REAL(KIND=4), DIMENSION(:),   ALLOCATABLE  :: e31d                 ! vertical metrics in case of full step
+   REAL(KIND=4), DIMENSION(:,:,:), ALLOCATABLE  :: zmask              ! npiglo x npjglo
+   REAL(KIND=4)                               :: rdep1, rdep2         ! depth counters
+   REAL(KIND=4)                               :: tol  = 1.0           ! tolerance 
+   REAL(KIND=4)                               :: sclf = 1.0           ! scale factor
+   REAL(KIND=4), PARAMETER                    :: ppspval= 9999.99     ! missing value
+
+   REAL(KIND=8)                               :: ds0=34.7             ! reference salinity
+   REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dfwc                ! fwc. as 2dim to be consistent with putvar()
+   REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE  :: dl_vint1, dl_vol2d   ! verticall int quantity         
+
+   CHARACTER(LEN=256)                         :: cf_in                ! input file
+   CHARACTER(LEN=256)                         :: cf_out='fwc.nc'      ! output file 
+   CHARACTER(LEN=256)                         :: cldum                ! dummy string for command line browsing
+   CHARACTER(LEN=256)                         :: cf_subbas='subbasins.nc'     ! subbasins file
+   CHARACTER(LEN=256)                         :: cv_cur               ! variable name
+
+  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_names           ! name of input variables
+  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_in              ! name of output variables
+
+
+
+   LOGICAL                                    :: lfull  =.FALSE.      ! flag for full step computation
+   LOGICAL                                    :: lchk   =.FALSE.      ! flag for missing files
+   LOGICAL                                    :: lsref  =.FALSE.      ! flag for user reference salinity
+   LOGICAL                                    :: laccum =.FALSE.      ! flag for accumulated fwc
+   LOGICAL                                    :: lssh   =.FALSE.      ! flag for using ssh for top layer thickness
+
+   TYPE(variable), DIMENSION(:), ALLOCATABLE  :: stypvarin            ! stucture for attributes (input)
+   TYPE(variable), DIMENSION(:), ALLOCATABLE  :: stypvar              ! extension for attributes
+   !!----------------------------------------------------------------------
+   CALL ReadCdfNames()
+
+   narg= iargc()
+   IF ( narg == 0 ) THEN
+      PRINT *,' usage : cdffwc IN-file BASIN-var1,var2,.. [-o OUT-file] [-sref REFSAL]'
+      PRINT *,'                [-full] [-accum] [-ssh]'
+      PRINT *,'      '
+      PRINT *,'     PURPOSE :'
+      PRINT *,'       Computes the freshwater content in a given basin from top'
+      PRINT *,'       to bottom for each layer. Can handle full step configuration'
+      PRINT *,'       using the -full option.'
+      PRINT *,'      '
+      PRINT *,'     ARGUMENTS :'
+      PRINT *,'        IN-file            : netcdf input file.' 
+      PRINT *,'        BASIN-var1,var2,.. : Comma separated list of sub-basin variables'
+      PRINT *,'                             to process.'
+      PRINT *,'        OUT-file           : use specified output file instead of <IN-var>.nc'
+      PRINT *,'      '
+      PRINT *,'     OPTIONS :'
+      PRINT *,'        -full  : for full step computation ' 
+      PRINT *,'        -accum : compute accumulated content from top to bottom' 
+      PRINT *,'        -ssh   : take ssh into account for surface layer' 
+      PRINT *,'        -sref  : reference salinity (= 34.7 by deafult)'
+      PRINT *,'      '
+      PRINT *,'     REQUIRED FILES :'
+      PRINT *,'       ', TRIM(cn_fzgr),', ',TRIM(cn_fhgr),' and ',TRIM(cf_subbas) ,' and ',TRIM(cn_fmsk)
+      PRINT *,'      '
+      PRINT *,'     OUTPUT : '
+      PRINT *,'       netcdf file :  fwc.nc (or specified with -o option)'
+      PRINT *,'         variables :  fwc_BASIN, where BASIN was set by argument BASIN-var*'
+      PRINT *,'                      (cAsE sensitive !)'
+      PRINT *,'      '
+      STOP
+   ENDIF
+
+
+   ! browse command line
+   ijarg = 1   ; ij = 0
+   DO WHILE ( ijarg <= narg ) 
+      CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1
+      SELECT CASE ( cldum)
+      CASE ( '-full' ) ; lfull  = .TRUE. 
+      CASE ( '-o'    ) ; CALL getarg (ijarg, cf_out) ; ijarg = ijarg + 1
+      CASE ( '-sref' ) ; lsref  = .TRUE. ; CALL getarg (ijarg, cldum) ; READ(cldum,*) ds0; ijarg = ijarg + 1
+      CASE ( '-accum') ; laccum = .TRUE. 
+      CASE ( '-ssh'  ) ; lssh   = .TRUE. 
+      CASE DEFAULT     
+         ij = ij + 1
+         SELECT CASE ( ij)
+         CASE ( 1 ) ; cf_in = cldum
+         CASE ( 2 ) ; CALL ParseVars(cldum)
+         CASE DEFAULT ; PRINT *, ' ERROR: Too many arguments ! ' ; STOP
+         END SELECT
+      END SELECT
+   END DO
+
+   ! Security check
+   lchk = chkfile ( cf_in   )
+   lchk = chkfile ( cn_fmsk ) .OR. lchk
+   lchk = chkfile ( cn_fhgr ) .OR. lchk
+   lchk = chkfile ( cn_fzgr ) .OR. lchk
+   lchk = chkfile (cf_subbas) .OR. lchk
+   IF ( lchk ) STOP ! missing files
+
+   sclf      = 1.
+
+   ! log information so far
+   PRINT *,' OUTPUT FILE     : ' , TRIM(cf_out)
+
+   npiglo = getdim (cf_in, cn_x )
+   npjglo = getdim (cf_in, cn_y )
+   npk    = getdim (cf_in, cn_z )
+   npt    = getdim (cf_in, cn_t )
+
+   PRINT *, ' NPIGLO = ', npiglo
+   PRINT *, ' NPJGLO = ', npjglo
+   PRINT *, ' NPK    = ', npk
+   PRINT *, ' NPT    = ', npt
+
+  nvars       = getnvar(cf_subbas)
+  
+  ALLOCATE(  cv_names( nvars       ) )
+  ALLOCATE( stypvarin( nvars       ) )
+  
+  ALLOCATE(   stypvar( nvaro       ) )
+  ALLOCATE(       ipk( nvaro       ) )
+  ALLOCATE( id_varout( nvaro       ) )
+  ALLOCATE(       dfwc( nvaro, 1, 1 ) )
+  
+  cv_names(:) = getvarname(cf_subbas, nvars, stypvarin)
+
+  ! just chck if var exist in file 
+  DO jvar = 1, nvaro
+     IF ( chkvar( cf_subbas, cv_in(jvar)) ) STOP  ! message is written in cdfio.chkvar
+  ENDDO
+
+   
+   ! Allocate arrays
+   ALLOCATE (      tim( npt                    ) )
+   ALLOCATE (    zmask( nvaro,   npiglo,npjglo ) )
+   ALLOCATE (    tmask(          npiglo,npjglo ) )
+   ALLOCATE (       zt(          npiglo,npjglo ) )
+   ALLOCATE (      e3t(          npiglo,npjglo ) )
+   ALLOCATE (     area(          npiglo,npjglo ) )
+   ALLOCATE ( dl_vint1(          npiglo,npjglo ) )
+   ALLOCATE ( dl_vol2d(          npiglo,npjglo ) )
+   IF ( lssh  ) ALLOCATE ( ssh(  npiglo,npjglo ) )
+   IF ( lfull ) ALLOCATE ( e31d( npk ) )
+
+   ! prepare output variable
+   ipk(:)                       = npk
+   write(cldum, *) ds0
+
+
+   DO jvar=1, nvaro     !Go through sub-basins
+     DO jvarin=1,nvars
+        IF ( cv_in(jvar) == stypvarin(jvarin)%cname ) EXIT  ! cv_in match cv_varin.
+     END DO
+     stypvar(jvar)%cname             = 'fwc_'//TRIM(cv_in(jvar))
+     stypvar(jvar)%cunits            = 'km3'
+     stypvar(jvar)%rmissing_value    = ppspval
+     stypvar(jvar)%valid_min         = 0.0
+     stypvar(jvar)%valid_max         = 0.0
+     IF ( laccum ) THEN 
+        stypvar(jvar)%clong_name        = 'freshwater content accumulated from top to bottom for '//TRIM(cv_in(jvar))//' based on S0='//TRIM(cldum)
+     ELSE
+        stypvar(jvar)%clong_name        = 'freshwater content per layer for '//TRIM(cv_in(jvar))//' based on S0='//TRIM(cldum)
+     ENDIF
+     stypvar(jvar)%clong_name        = 'freshwater content for '//TRIM(cv_in(jvar))//' based on S0='//TRIM(cldum)
+     stypvar(jvar)%cshort_name       = 'fwc_'//TRIM(cv_in(jvar))
+     stypvar(jvar)%conline_operation = 'N/A'
+     stypvar(jvar)%caxis             = 'T'
+   END DO
+
+ 
+   ! Read area field
+   area(:,:)   = getvar(cn_fhgr  , cn_ve1t,  1, npiglo, npjglo)  ! Save memory: e1t is first read into area
+   zt(  :,:)   = getvar(cn_fhgr  , cn_ve2t,  1, npiglo, npjglo)  ! ..and zv is used to read e2t
+   area(:,:)   = area(:,:) * zt(:,:)                             ! ..
+
+   ! Read vertical axis in full-step-case
+   IF ( lfull ) e31d(:) = getvare3(cn_fzgr, cn_ve3t, npk)
+
+   ! Read sub-basin masks (2D) and keep them for all layers
+   DO jvar = 1,nvaro          ! Loop through sub-basins
+        zmask(jvar,:,:) = getvar(cf_subbas, cv_in(jvar) ,  1, npiglo, npjglo )
+   END DO
+   
+   ! Initialize output file
+   ncout = create      (cf_out, 'none', 1, 1, npk, cdep=cn_vdepthw, ld_xycoo=.FALSE. )
+   ierr  = createvar   (ncout, stypvar, nvaro, ipk, id_varout)
+   ierr  = putheadervar(ncout, cf_in,   1, 1, npk,     ld_xycoo=.FALSE.)
+   
+   tim   = getvar1d    (cf_in, cn_vtimec, npt     )
+   ierr  = putvar1d    (ncout, tim,       npt, 'T')
+
+   
+   
+   PRINT *, 'Output files initialised ...'
+
+
+   DO jt=1,npt
+        dl_vol2d(  :,:) = 0.d0
+        dl_vint1(  :,:) = 0.d0
+             dfwc(:,:,:) = 0.d0
+        IF ( lssh ) ssh(:,:) = 0.e0
+
+        DO jk = 1, npk
+           ! Get values at jk
+           zt(   :,:) = getvar(cf_in,     cn_vosaline, jk, npiglo, npjglo, ktime=jt)     ! Read Salinity(2D) at level jk and time step jt
+           tmask(:,:) = getvar(cn_fmsk,       'tmask', jk, npiglo, npjglo          )
+           
+           ! get e3t at level jk ( ps...)
+           IF ( lfull ) THEN ; e3t(:,:) = e31d(jk)
+           ELSE              ; e3t(:,:) = getvar(cn_fzgr, 'e3t_ps', jk, npiglo, npjglo, ldiom=.TRUE.)
+           ENDIF
+           
+           IF ( jk == 1 .AND. lssh ) THEN
+                ssh(:,:) = getvar(cf_in,     cn_sossheig, 1, npiglo, npjglo, ktime=jt)
+                e3t(:,:) = e3t(:,:) + ssh(:,:)
+           ENDIF
+           
+           DO jvar = 1,nvaro          ! Loop through sub-basins
+            
+                dl_vol2d     = area * e3t * tmask * zmask(jvar,:,:) * 1.d0
+
+                dl_vint1   = ( ds0 - zt ) / ds0 * dl_vol2d
+                IF ( laccum ) THEN
+                    dfwc(jvar,1,1)   = SUM( dl_vint1 ) + dfwc(jvar,1,1)
+                ELSE
+                    dfwc(jvar,1,1)   = SUM( dl_vint1 )
+                ENDIF
+
+                ! Output to netcdf file 
+                ierr = putvar(ncout, id_varout(jvar), REAL(dfwc(jvar,:,:)), jk, 1, 1, ktime=jt)
+            
+           END DO   ! jvar
+        
+        END DO
+        
+   END DO  ! loop on time
+
+
+   ierr = closeout(ncout)
+
+  CONTAINS
+  
+  SUBROUTINE ParseVars (cdum)
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE ParseVars  ***
+    !!
+    !! ** Purpose :  Decode variable name  option from command line
+    !!
+    !! ** Method  :  look for , in the argument string and set the number of
+    !!         variable (nvaro), allocate cv_in array and fill it with the
+    !!         decoded  names.
+    !!
+    !!----------------------------------------------------------------------
+    CHARACTER(LEN=*), INTENT(in) :: cdum
+
+    CHARACTER(LEN=80), DIMENSION(100) :: cl_dum  ! 100 is arbitrary
+    INTEGER  :: ji
+    INTEGER  :: inchar,  i1=1
+    !!----------------------------------------------------------------------
+    inchar= LEN(TRIM(cdum))
+    ! scan the input string and look for ',' as separator
+    DO ji=1,inchar
+       IF ( cdum(ji:ji) == ',' ) THEN
+          cl_dum(nvaro) = cdum(i1:ji-1)
+          i1=ji+1
+          nvaro=nvaro+1
+       ENDIF
+    ENDDO
+
+    ! last name of the list does not have a ','
+    cl_dum(nvaro) = cdum(i1:inchar)
+
+    ALLOCATE ( cv_in(nvaro) )
+    DO ji=1, nvaro
+       cv_in(ji) = cl_dum(ji)
+    ENDDO
+  END SUBROUTINE ParseVars
+
+
+END PROGRAM cdffwc
diff --git a/cdfgeo-uv.f90 b/src/cdfgeo-uv.f90
similarity index 55%
rename from cdfgeo-uv.f90
rename to src/cdfgeo-uv.f90
index febd6f7..c2f051c 100644
--- a/cdfgeo-uv.f90
+++ b/src/cdfgeo-uv.f90
@@ -29,9 +29,11 @@ PROGRAM cdfgeo_uv
   INTEGER(KIND=4)                           :: npiglo, npjglo ! size of the domain
   INTEGER(KIND=4)                           :: npk, npt       ! size of the domain
   INTEGER(KIND=4)                           :: narg, iargc    ! browse line
+  INTEGER(KIND=4)                           :: ijarg          ! browse line
   INTEGER(KIND=4)                           :: ncoutu         ! ncid for ugeo file
   INTEGER(KIND=4)                           :: ncoutv         ! ncid for vgeo file
   INTEGER(KIND=4)                           :: ierr           ! error status
+  INTEGER(KIND=4)                           :: ioption=0      ! Option for C-grid interpolation
   INTEGER(KIND=4), DIMENSION(1)             :: ipk            ! levels of output vars
   INTEGER(KIND=4), DIMENSION(1)             :: id_varoutu     ! varid for ugeo
   INTEGER(KIND=4), DIMENSION(1)             :: id_varoutv     ! varid for vgeo
@@ -40,15 +42,20 @@ PROGRAM cdfgeo_uv
   REAL(KIND=4)                              :: ffu, ffv       ! coriolis param f at U and V point
   REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim            ! time counter
   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e1u, e2v, ff   ! horiz metrics, coriolis (f-point)
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e2u, e1v       ! horiz metrics
   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: glamu, gphiu   ! longitude latitude u-point
   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: glamv, gphiv   ! longitude latitude v-point
   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: un, vn         ! velocity components
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zun, zvn       ! velocity components
   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zsshn          ! ssh
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zwrk           ! working array for interpolation
   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: umask, vmask   ! mask at u and v points
 
   CHARACTER(LEN=256)                        :: cf_tfil        ! input file name
   CHARACTER(LEN=256)                        :: cf_uout='ugeo.nc' 
   CHARACTER(LEN=256)                        :: cf_vout='vgeo.nc'
+  CHARACTER(LEN=256)                        :: cl_dum         ! dummy character variable
+  CHARACTER(LEN=256)                        :: cl_global      ! global attribute
 
   TYPE(variable), DIMENSION(1)              :: stypvaru       ! attributes for ugeo
   TYPE(variable), DIMENSION(1)              :: stypvarv       ! attributes for vgeo
@@ -61,31 +68,72 @@ PROGRAM cdfgeo_uv
 
   narg = iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfgeo-uv T-file'
+     PRINT *,' usage : cdfgeo-uv -f T-file [-o UOUT-file VOUT-file ] [ -C option ]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
-     PRINT *,'       Compute the geostrophic velocity component from the gradient '
-     PRINT *,'       of the SSH read in the input file. Note that in the C-grid '
-     PRINT *,'       output file, the zonal component is located on V point and the'
-     PRINT *,'       meridional component is located on U point.'
+     PRINT *,'         Compute the geostrophic velocity component from the gradient '
+     PRINT *,'       of the SSH read in the input file. '
+     PRINT *,'         Without any -C option, the zonal component is located on a '
+     PRINT *,'       C-grid V point, the meridional one is located on C-Grid U point.'
+     PRINT *,'         See the use of the -C option in order to have (Ugeo, Vgeo) '
+     PRINT *,'       at (U,V) points on the C-grid.'
      PRINT *,'      '
      PRINT *,'     ARGUMENTS :'
-     PRINT *,'       T-file : netcdf file with SSH.' 
+     PRINT *,'      -f  T-file : netcdf file with SSH (input).' 
      PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'      -o UOUT-file VOUT-file: specify the names of the output files.'
+     PRINT *,'                Default are: ',TRIM(cf_uout),' ',TRIM(cf_vout),'.'
+     PRINT *,'      -C option : Using this option, the output velocity component are'
+     PRINT *,'               at the correct (U,V) points on the C-grid'
+     PRINT *,'               2 options are available :'
+     PRINT *,'              option = 1 : SSH is interpolated on the F point prior derivation'
+     PRINT *,'              option = 2 : Ugeo and Vgeo are interpolated on the C-grid after'
+     PRINT *,'                     derivation'
+     PRINT *,'                 Both option should give very similar results...'
+     PRINT *,'  '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'        ',TRIM(cn_fhgr),' and ',TRIM(cn_fzgr)
      PRINT *,'      '
      PRINT *,'     OUTPUT : '
-     PRINT *,'       - netcdf file : ', TRIM(cf_uout) 
+     PRINT *,'       - netcdf file : ', TRIM(cf_uout) ,' (default)'
      PRINT *,'           variables : ', TRIM(cn_vozocrtx)
+     PRINT *,'           Unless -C option is used : '
      PRINT *,'             *** CAUTION:  this variable is located on V-point ***'
-     PRINT *,'       - netcdf file : ', TRIM(cf_vout) 
+     PRINT *,'       - netcdf file : ', TRIM(cf_vout) ,' (default)'
      PRINT *,'           variables : ', TRIM(cn_vomecrty)
+     PRINT *,'           Unless -C option is used : '
      PRINT *,'             *** CAUTION:  this variable is located on U-point ***'
      STOP
   ENDIF
 
-  CALL getarg(1, cf_tfil)
+  cl_global=' (Ugeo, Vgeo ) are on ( V, U ) points of the C-grid'
+  ijarg = 1
+  DO WHILE ( ijarg <= narg )
+    CALL getarg(ijarg, cl_dum ) ; ijarg = ijarg + 1
+    SELECT CASE ( cl_dum )
+    CASE ('-f' ) 
+       CALL getarg(ijarg, cf_tfil ) ; ijarg = ijarg + 1 
+    CASE ('-o' ) 
+       CALL getarg(ijarg, cf_uout ) ; ijarg = ijarg + 1
+       CALL getarg(ijarg, cf_vout ) ; ijarg = ijarg + 1
+    CASE ('-C' ) 
+       CALL getarg(ijarg, cl_dum ) ; ijarg = ijarg + 1
+       READ(cl_dum, * ) ioption
+       IF ( ioption == 1 ) THEN
+         PRINT *,'  *** Use SSH interpolation ***'
+         cl_global=' (Ugeo, Vgeo ) are on ( U, V ) points of the C-grid (SSH interp)'
+       ELSEIF ( ioption == 2 ) THEN
+         PRINT *,'  *** Use Ugeo Vgeo interpolation ***'
+         cl_global=' (Ugeo, Vgeo ) are on ( U, V ) points of the C-grid (velocity interp)'
+       ELSE
+         PRINT *, ' +++ ERROR: -C can use only option 1 or 2 +++'
+         STOP
+       ENDIF
+    CASE DEFAULT
+       PRINT *, '  +++ ERROR: Argument ',TRIM(cl_dum),' not supported. +++'
+    END SELECT
+  ENDDO
 
   lchk = chkfile(cn_fhgr)
   lchk = chkfile(cn_fzgr) .OR. lchk
@@ -125,16 +173,21 @@ PROGRAM cdfgeo_uv
 
   ! Allocate the memory
   ALLOCATE ( e1u(npiglo,npjglo), e2v(npiglo,npjglo) )
+  IF( ioption == 1 ) ALLOCATE ( e1v(npiglo,npjglo), e2u(npiglo,npjglo) )
   ALLOCATE ( ff(npiglo,npjglo), tim(npt)  )
   ALLOCATE ( glamu(npiglo,npjglo), gphiu(npiglo,npjglo)  )
   ALLOCATE ( glamv(npiglo,npjglo), gphiv(npiglo,npjglo)  )
   ALLOCATE ( un(npiglo,npjglo), vn(npiglo,npjglo)  )
+  IF ( ioption == 2 ) ALLOCATE ( zun(npiglo,npjglo), zvn(npiglo,npjglo)  )
   ALLOCATE ( zsshn(npiglo,npjglo) )
   ALLOCATE ( umask(npiglo,npjglo), vmask(npiglo,npjglo) )
+  ALLOCATE ( zwrk (npiglo,npjglo) )
 
   ! Read the metrics from the mesh_hgr file
-  e2v   = getvar(cn_fhgr, cn_ve2v,  1, npiglo, npjglo)
   e1u   = getvar(cn_fhgr, cn_ve1u,  1, npiglo, npjglo)
+  e1v   = getvar(cn_fhgr, cn_ve1v,  1, npiglo, npjglo)
+  e2u   = getvar(cn_fhgr, cn_ve2u,  1, npiglo, npjglo)
+  e2v   = getvar(cn_fhgr, cn_ve2v,  1, npiglo, npjglo)
   ff    = getvar(cn_fhgr, cn_vff,   1, npiglo, npjglo) 
 
   glamu = getvar(cn_fhgr, cn_glamu, 1, npiglo, npjglo)
@@ -143,44 +196,65 @@ PROGRAM cdfgeo_uv
   gphiv = getvar(cn_fhgr, cn_gphiv, 1, npiglo, npjglo)
 
   ! create output filesets
-  ! U geo  ! @ V-point !
   ncoutu = create      (cf_uout, cf_tfil,  npiglo, npjglo, 0                              )
-  ierr   = createvar   (ncoutu,  stypvaru, 1,      ipk,    id_varoutu                     )
-  ierr   = putheadervar(ncoutu,  cf_tfil,  npiglo, npjglo, 0, pnavlon=glamv, pnavlat=gphiv)
+  ierr   = createvar   (ncoutu,  stypvaru, 1,      ipk,    id_varoutu, cdglobal=cl_global )
+  IF ( ioption == 0 ) THEN
+    ! U geo  ! @ V-point !
+     ierr   = putheadervar(ncoutu,  cf_tfil,  npiglo, npjglo, 0, pnavlon=glamv, pnavlat=gphiv)
+  ELSE
+     ierr   = putheadervar(ncoutu,  cf_tfil,  npiglo, npjglo, 0, pnavlon=glamu, pnavlat=gphiu)
+  ENDIF
   
   tim  = getvar1d(cf_tfil, cn_vtimec, npt     )
   ierr = putvar1d(ncoutu,  tim,       npt, 'T')
 
   ! V geo  ! @ U-point !
   ncoutv = create      (cf_vout, cf_tfil,  npiglo, npjglo, 0                              )
-  ierr   = createvar   (ncoutv,  stypvarv, 1,      ipk,    id_varoutv                     )
-  ierr   = putheadervar(ncoutv,  cf_tfil,  npiglo, npjglo, 0, pnavlon=glamu, pnavlat=gphiu)
+  ierr   = createvar   (ncoutv,  stypvarv, 1,      ipk,    id_varoutv, cdglobal=cl_global )
+  IF ( ioption == 0 ) THEN
+    ! V geo  ! @ U-point !
+     ierr   = putheadervar(ncoutv,  cf_tfil,  npiglo, npjglo, 0, pnavlon=glamu, pnavlat=gphiu)
+  ELSE
+     ierr   = putheadervar(ncoutv,  cf_tfil,  npiglo, npjglo, 0, pnavlon=glamv, pnavlat=gphiv)
+  ENDIF
 
   tim  = getvar1d(cf_tfil, cn_vtimec, npt     )
   ierr = putvar1d(ncoutv,  tim,       npt, 'T')
 
   ! Read ssh
   DO jt=1,npt
-     zsshn = getvar(cf_tfil, cn_sossheig, 1, npiglo, npjglo, ktime=jt)
+     zwrk(:,:) = getvar(cf_tfil, cn_sossheig, 1, npiglo, npjglo, ktime=jt)
+     IF ( ioption == 1 ) THEN
+        PRINT *, ' *** interpolation of SSH ...'
+       DO jj=1, npjglo -1
+         DO ji=1, npiglo -1
+            zsshn(ji,jj) = 0.25*( zwrk (ji,jj  ) +  zwrk (ji+1,jj  ) + &
+               &                  zwrk (ji,jj+1) +  zwrk (ji+1,jj+1) )
+         ENDDO
+       ENDDO
+     ELSE
+        zsshn(:,:) = zwrk(:,:) 
+     ENDIF
 
      IF ( jt == 1 ) THEN
         ! compute the masks
         umask=0. ; vmask = 0
         DO jj = 1, npjglo 
            DO ji = 1, npiglo - 1
-              umask(ji,jj) = zsshn(ji,jj)*zsshn(ji+1,jj)
+              umask(ji,jj) = zwrk(ji,jj)*zwrk(ji+1,jj)
               IF (umask(ji,jj) /= 0.) umask(ji,jj) = 1.
            END DO
         END DO
 
         DO jj = 1, npjglo - 1
            DO ji = 1, npiglo
-              vmask(ji,jj) = zsshn(ji,jj)*zsshn(ji,jj+1)
+              vmask(ji,jj) = zwrk(ji,jj)*zwrk(ji,jj+1)
               IF (vmask(ji,jj) /= 0.) vmask(ji,jj) = 1.
            END DO
         END DO
         ! e1u and e1v are modified to simplify the computation below
         ! note that geostrophy is not available near the equator ( f=0)
+        IF ( ioption == 0 .OR. ioption == 2 ) THEN  ! SSH at T point
         DO jj=2, npjglo - 1
            DO ji=2, npiglo - 1
               ffu = ff(ji,jj) + ff(ji,  jj-1)
@@ -198,18 +272,60 @@ PROGRAM cdfgeo_uv
               ENDIF
            END DO
         END DO
+        ELSE    ! SSH at F point
+        DO jj=2, npjglo - 1
+           DO ji=2, npiglo - 1
+              ffu = ff(ji,jj) + ff(ji,  jj-1)
+              IF ( ffu /= 0. ) THEN
+                e2u(ji,jj)= 2.* grav * umask(ji,jj) / ( ffu ) / e2u(ji,jj)
+              ELSE
+                e2u(ji,jj)= 0.  ! spvalue
+              ENDIF
+
+              ffv = ff(ji,jj) + ff(ji-1,jj  )
+              IF ( ffv /= 0. ) THEN
+                e1v(ji,jj)= 2.* grav * vmask(ji,jj) / ( ffv ) / e1v(ji,jj)
+              ELSE
+                e1v(ji,jj)= 0.  ! spvalue
+              ENDIF
+           END DO
+        ENDDO
+
+        ENDIF
+       
      END IF
 
      ! Calculation of geostrophic velocity :
      un(:,:) = 0.
      vn(:,:) = 0.
 
-     DO jj = 2,npjglo - 1
-        DO ji = 2,npiglo -1
-           vn(ji,jj) = e1u(ji,jj) * ( zsshn(ji+1,jj  ) - zsshn(ji,jj) ) 
-           un(ji,jj) = e2v(ji,jj) * ( zsshn(ji  ,jj+1) - zsshn(ji,jj) ) 
+     IF ( ioption == 0 .OR. ioption == 2 ) THEN
+     DO jj = 1,npjglo - 1
+        DO ji = 1,npiglo -1
+           vn(ji,jj) =   e1u(ji,jj) * ( zsshn(ji+1,jj  ) - zsshn(ji,jj) ) 
+           un(ji,jj) = - e2v(ji,jj) * ( zsshn(ji  ,jj+1) - zsshn(ji,jj) ) 
+        END DO
+     END DO
+     ELSE    ! SSH at F point
+     DO jj = 2,npjglo 
+        DO ji = 2,npiglo 
+           vn(ji,jj) =   e1v(ji,jj) * ( zsshn(ji,jj) - zsshn(ji-1,jj) ) 
+           un(ji,jj) = - e2u(ji,jj) * ( zsshn(ji,jj) - zsshn(ji,jj-1) ) 
         END DO
      END DO
+     ENDIF
+
+     IF ( ioption == 2 ) THEN ! interpolate ugeo, vgeo on (U,V) point
+        PRINT *, ' *** interpolation of velocities ...'
+        DO jj=2,npjglo -1
+         DO ji=2, npiglo -1
+            zun(ji,jj) = 0.25*( un(ji,jj) + un(ji, jj-1) + un(ji+1,jj) + un (ji+1, jj-1) )
+            zvn(ji,jj) = 0.25*( vn(ji,jj) + vn(ji-1, jj) + vn(ji,jj+1) + vn (ji-1, jj+1) )
+         ENDDO
+        ENDDO
+        un(:,:) = zun(:,:)
+        vn(:,:) = zvn(:,:)
+     ENDIF
 
      ! write un and vn  ...
      ierr = putvar(ncoutu, id_varoutu(1), un(:,:), 1, npiglo, npjglo, ktime=jt)
diff --git a/cdfgeostrophy.f90 b/src/cdfgeostrophy.f90
similarity index 100%
rename from cdfgeostrophy.f90
rename to src/cdfgeostrophy.f90
diff --git a/src/cdfgradT.f90 b/src/cdfgradT.f90
new file mode 100644
index 0000000..91fb3ee
--- /dev/null
+++ b/src/cdfgradT.f90
@@ -0,0 +1,280 @@
+PROGRAM cdfgradT
+   !!======================================================================
+   !!                     ***  PROGRAM  cdfgradT ***
+   !!=====================================================================
+   !!  ** Purpose :
+   !!
+   !!  ** Method  :
+   !!
+   !! History : 3.0  : 05/2013  : N. Ducousso
+   !!           3.0  : 06/2013  : J.M. Molines : Doctor norm + Lic.
+   !!----------------------------------------------------------------------
+   !!----------------------------------------------------------------------
+   !!   routines      : description
+   !!   CreateOutput  :  perform all the stuff linked with output file 
+   !!----------------------------------------------------------------------
+   USE cdfio
+   USE modcdfnames
+   !!----------------------------------------------------------------------
+   !! CDFTOOLS_3.0 , MEOM 2012
+   !! $Id$
+   !! Copyright (c) 2012, J.-M. Molines
+   !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+   !!----------------------------------------------------------------------
+   IMPLICIT NONE
+
+   INTEGER(KIND=4), PARAMETER                  :: jp_varout = 6     ! number of output variables
+   INTEGER(KIND=4)                             :: jk, jt            ! dummy loop index
+   INTEGER(KIND=4)                             :: narg, iargc       ! command line
+   INTEGER(KIND=4)                             :: npiglo, npjglo    ! size of the domain
+   INTEGER(KIND=4)                             :: npk, npt          ! size of the domain
+   INTEGER(KIND=4)                             :: ncout             ! ncid of output variable
+   INTEGER(KIND=4)                             :: ierr              ! error status
+   INTEGER(KIND=4)                             :: iup = 1, icur = 2 ! 2 working level
+   INTEGER(KIND=4)                             :: itmp              ! working integer for swapping arrays
+   INTEGER(KIND=4), DIMENSION(jp_varout)       :: ipk, id_varout    ! output variable
+
+   REAL(KIND=4), DIMENSION(:),     ALLOCATABLE :: tim               ! time variable
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: umask, vmask, wmask ! relevant mask
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: e1u, e2v, e3w     ! metrics
+   REAL(KIND=4), DIMENSION(:,:,:), ALLOCATABLE :: zt, zs            ! Temperature Salinity on 2 levels
+
+   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dgradt_x, dgradt_y, dgradt_z  ! Temperature gradient component
+   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dgrads_x, dgrads_y, dgrads_z  ! Salinity gradient component
+
+   CHARACTER(LEN=256)                         :: cf_tfil             ! input file name for T and S
+   CHARACTER(LEN=256)                         :: cf_sfil             ! input file name for S (optional)
+   CHARACTER(LEN=256)                         :: cf_out = 'gradT.nc' ! output file name
+
+   TYPE(variable), DIMENSION(jp_varout)       :: stypvar             ! output data structure
+
+   LOGICAL                                    :: lchk = .FALSE.      ! flag for missing files
+   !!----------------------------------------------------------------------
+   CALL ReadCdfNames()
+
+   narg= iargc()
+   IF ( narg == 0 ) THEN
+      PRINT *,' usage : cdfgradT T-file [S-file] '
+      PRINT *,'      '
+      PRINT *,'     PURPOSE :'
+      PRINT *,'        Compute horizontal and vertical gradient of temperature and salinity.'
+      PRINT *,'      Results are saved at U point for zonal gradient, V point for meridional'
+      PRINT *,'      gradient and W for vertical gradient.'
+      PRINT *,'      '
+      PRINT *,'     ARGUMENTS :'
+      PRINT *,'       T-file : File with ',TRIM(cn_votemper),' and ',TRIM(cn_vosaline),' variables' 
+      PRINT *,'           If ',TRIM(cn_vosaline),' not in T-file give a second name for S-file.'
+      PRINT *,'      '
+      PRINT *,'     OPTIONS :'
+      PRINT *,'       S-file : File with ',TRIM(cn_vosaline),' variable if not in T file'
+      PRINT *,'      '
+      PRINT *,'     REQUIRED FILES :'
+      PRINT *,'       ', TRIM(cn_fhgr),' ',TRIM(cn_fmsk),' and ',TRIM(cn_fzgr)
+      PRINT *,'      '
+      PRINT *,'     OUTPUT : '
+      PRINT *,'       netcdf file : ', TRIM(cf_out) 
+      PRINT *,'         ',jp_varout,' variables : '
+      PRINT *,'              vozogradt, vomegradt, vovegradt : 3 component of the temperature'
+      PRINT *,'                          located respectively at U, V and W points'
+      PRINT *,'              vozograds, vomegrads, vovegrads : 3 component of the salinity'
+      PRINT *,'                          located respectively at U, V and W points'
+      PRINT *,'      '
+      PRINT *,'     SEE ALSO :'
+      PRINT *,'      '
+      PRINT *,'      '
+      STOP
+   ENDIF
+
+   CALL getarg (1, cf_tfil)
+   IF ( narg == 2 ) THEN
+      CALL getarg( 2, cf_sfil)
+   ELSE
+      cf_sfil = cf_tfil   ! ff only one file provided, they are identical
+   ENDIF
+
+   lchk = ( lchk .OR. chkfile(cf_tfil) )
+   lchk = ( lchk .OR. chkfile(cf_sfil) )
+   lchk = ( lchk .OR. chkfile(cn_fhgr) )
+   lchk = ( lchk .OR. chkfile(cn_fzgr) )
+   lchk = ( lchk .OR. chkfile(cn_fmsk) )
+   IF (lchk ) STOP ! missing file
+
+   npiglo = getdim (cf_tfil, cn_x)
+   npjglo = getdim (cf_tfil, cn_y)
+   npk    = getdim (cf_tfil, cn_z)
+   npt    = getdim (cf_tfil, cn_t)
+
+   PRINT *, 'npiglo = ', npiglo
+   PRINT *, 'npjglo = ', npjglo
+   PRINT *, 'npk    = ', npk
+   PRINT *, 'npt    = ', npt
+
+   !!  Allocate arrays
+   ALLOCATE (tim(npt) )
+   ALLOCATE (e1u  (npiglo,npjglo), e2v  (npiglo,npjglo), e3w  (npiglo,npjglo))
+   ALLOCATE (umask(npiglo,npjglo), vmask(npiglo,npjglo), wmask(npiglo,npjglo))
+   ALLOCATE (zt   (npiglo,npjglo,2), zs (npiglo,npjglo,2))
+   ALLOCATE (dgradt_x(npiglo,npjglo), dgradt_y(npiglo,npjglo), dgradt_z(npiglo,npjglo))
+   ALLOCATE (dgrads_x(npiglo,npjglo), dgrads_y(npiglo,npjglo), dgrads_z(npiglo,npjglo))
+
+   CALL CreateOutput
+
+   tim  = getvar1d(cf_tfil, cn_vtimec, npt     )
+   ierr = putvar1d(ncout,  tim,        npt, 'T')
+
+   e1u =  getvar(cn_fhgr, cn_ve1u, 1, npiglo, npjglo)
+   e2v =  getvar(cn_fhgr, cn_ve2v, 1, npiglo, npjglo)
+
+   DO jt = 1,npt
+      DO jk = npk, 1, -1  !! Main loop : (2 levels of T are required : iup, icur)
+
+         PRINT *,'level ',jk
+         ! read files
+         IF ( jk == npk   ) THEN  ! first time need to read 2 levels
+            zt(:,:,iup ) = getvar(cf_tfil, cn_votemper, jk-1, npiglo, npjglo, ktime=jt)
+            zt(:,:,icur) = getvar(cf_tfil, cn_votemper, jk,   npiglo, npjglo, ktime=jt)
+            zs(:,:,iup ) = getvar(cf_sfil, cn_vosaline, jk-1, npiglo, npjglo, ktime=jt)
+            zs(:,:,icur) = getvar(cf_sfil, cn_vosaline, jk,   npiglo, npjglo, ktime=jt)
+         ELSEIF ( jk == 1 ) THEN ! surface : vertical gradient is N/A
+            iup = icur        
+         ELSE                  ! only read iup, icur has been swapped
+            zt(:,:,iup ) = getvar(cf_tfil, cn_votemper, jk-1, npiglo, npjglo, ktime=jt)
+            zs(:,:,iup ) = getvar(cf_sfil, cn_vosaline, jk-1, npiglo, npjglo, ktime=jt)
+         ENDIF
+
+!        IF (jk == 1) THEN
+!           zt(:,:,iup ) = getvar(cf_tfil, cn_votemper, jk, npiglo, npjglo, ktime=jt)
+!           zt(:,:,icur) = getvar(cf_tfil, cn_votemper, jk, npiglo, npjglo, ktime=jt)
+!           zs(:,:,iup ) = getvar(cf_sfil, cn_vosaline, jk, npiglo, npjglo, ktime=jt)
+!           zs(:,:,icur) = getvar(cf_sfil, cn_vosaline, jk, npiglo, npjglo, ktime=jt)
+!        ELSE        
+!           zt(:,:,iup ) = getvar(cf_tfil, cn_votemper, jk-1, npiglo, npjglo, ktime=jt)
+!           zt(:,:,icur) = getvar(cf_tfil, cn_votemper, jk,   npiglo, npjglo, ktime=jt)
+!           zs(:,:,iup ) = getvar(cf_sfil, cn_vosaline, jk-1, npiglo, npjglo, ktime=jt)
+!           zs(:,:,icur) = getvar(cf_sfil, cn_vosaline, jk,   npiglo, npjglo, ktime=jt)
+!        END IF
+
+         e3w(:,:)   = getvar(cn_fzgr, 'e3w_ps', jk, npiglo, npjglo, ldiom=.TRUE.)
+
+         umask(:,:) = getvar(cn_fmsk, 'umask' , jk, npiglo, npjglo )
+         vmask(:,:) = getvar(cn_fmsk, 'vmask' , jk, npiglo, npjglo )
+         wmask(:,:) = getvar(cn_fmsk, 'tmask' , jk, npiglo, npjglo )
+
+         ! zonal grad located at U point at current level
+         dgradt_x(:,:) = 0.d0
+         dgradt_x(1:npiglo-1,:) = 1.d0 / e1u(1:npiglo-1,:) * &
+              &                 ( zt(2:npiglo,:,icur) - zt(1:npiglo-1,:,icur) ) * umask(1:npiglo-1,:)
+         dgrads_x(:,:) = 0.d0
+         dgrads_x(1:npiglo-1,:) = 1.d0 / e1u(1:npiglo-1,:) * &
+              &                 ( zs(2:npiglo,:,icur) - zs(1:npiglo-1,:,icur) ) * umask(1:npiglo-1,:)
+
+         ! meridional grad located at V point at current level
+         dgradt_y(:,:) = 0.d0
+         dgradt_y(:,1:npjglo-1) = 1.d0 / e2v(:,1:npjglo-1) * &
+              &                 ( zt(:,2:npjglo,icur) - zt(:,1:npjglo-1,icur) ) * vmask(:,1:npjglo-1)
+         dgrads_y(:,:) = 0.d0
+         dgrads_y(:,1:npjglo-1) = 1.d0 / e2v(:,1:npjglo-1) * &
+              &                 ( zs(:,2:npjglo,icur) - zs(:,1:npjglo-1,icur) ) * vmask(:,1:npjglo-1)
+
+         ! vertical grad located at W point 
+         dgradt_z(:,:) = 0.d0
+         dgradt_z(:,:) = 1.d0 / e3w(:,:) * ( zt(:,:,iup) - zt(:,:,icur) ) * wmask(:,:)
+         dgrads_z(:,:) = 0.d0
+         dgrads_z(:,:) = 1.d0 / e3w(:,:) * ( zs(:,:,iup) - zs(:,:,icur) ) * wmask(:,:)
+
+         ! write
+         ierr = putvar(ncout, id_varout(1), REAL(dgradt_x), jk, npiglo, npjglo, ktime=jt)
+         ierr = putvar(ncout, id_varout(2), REAL(dgradt_y), jk, npiglo, npjglo, ktime=jt)
+         ierr = putvar(ncout, id_varout(3), REAL(dgradt_z), jk, npiglo, npjglo, ktime=jt)
+         ierr = putvar(ncout, id_varout(4), REAL(dgrads_x), jk, npiglo, npjglo, ktime=jt)
+         ierr = putvar(ncout, id_varout(5), REAL(dgrads_y), jk, npiglo, npjglo, ktime=jt)
+         ierr = putvar(ncout, id_varout(6), REAL(dgrads_z), jk, npiglo, npjglo, ktime=jt)
+        
+         ! swap levels and read only up
+         itmp = iup ; iup  = icur ; icur = itmp
+
+      END DO
+   END DO
+
+   ierr = closeout(ncout)
+
+CONTAINS
+   SUBROUTINE CreateOutput
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE CreateOutput  ***
+      !!
+      !! ** Purpose :  Set up all things required for the output file, create
+      !!               the file and write the header part. 
+      !!
+      !! ** Method  :  Use global module variables 
+      !!
+      !!----------------------------------------------------------------------
+      ipk(:) = npk  !  3D
+
+      stypvar(1)%cname             = 'vozogradt'
+      stypvar(1)%cunits            = ''
+      stypvar(1)%rmissing_value    = -1000.
+      stypvar(1)%valid_min         = -1.
+      stypvar(1)%valid_max         = 1.
+      stypvar(1)%clong_name        = 'zonal temper gradient'
+      stypvar(1)%cshort_name       = 'vozogradt'
+      stypvar(1)%conline_operation = 'N/A'
+      stypvar(1)%caxis             = 'TZYX'
+
+      stypvar(2)%cname             = 'vomegradt'
+      stypvar(2)%cunits            = ''
+      stypvar(2)%rmissing_value    = -1000.
+      stypvar(2)%valid_min         = -1.
+      stypvar(2)%valid_max         = 1.
+      stypvar(2)%clong_name        = 'meridional temper gradient'
+      stypvar(2)%cshort_name       = 'vomegradt'
+      stypvar(2)%conline_operation = 'N/A'
+      stypvar(2)%caxis             = 'TZYX'
+
+      stypvar(3)%cname             = 'vovegradt'
+      stypvar(3)%cunits            = ''
+      stypvar(3)%rmissing_value    = -1000.
+      stypvar(3)%valid_min         = -1.
+      stypvar(3)%valid_max         = 1.
+      stypvar(3)%clong_name        = 'vertical temper gradient'
+      stypvar(3)%cshort_name       = 'vovegradt'
+      stypvar(3)%conline_operation = 'N/A'
+      stypvar(3)%caxis             = 'TZYX'
+
+      stypvar(4)%cname             = 'vozograds'
+      stypvar(4)%cunits            = ''
+      stypvar(4)%rmissing_value    = -1000.
+      stypvar(4)%valid_min         = -1.
+      stypvar(4)%valid_max         = 1.
+      stypvar(4)%clong_name        = 'zonal saline gradient'
+      stypvar(4)%cshort_name       = 'vozograds'
+      stypvar(4)%conline_operation = 'N/A'
+      stypvar(4)%caxis             = 'TZYX'
+
+      stypvar(5)%cname             = 'vomegrads'
+      stypvar(5)%cunits            = ''
+      stypvar(5)%rmissing_value    = -1000.
+      stypvar(5)%valid_min         = -1.
+      stypvar(5)%valid_max         = 1.
+      stypvar(5)%clong_name        = 'meridional saline gradient'
+      stypvar(5)%cshort_name       = 'vomegrads'
+      stypvar(5)%conline_operation = 'N/A'
+      stypvar(5)%caxis             = 'TZYX'
+
+      stypvar(6)%cname             = 'vovegrads'
+      stypvar(6)%cunits            = ''
+      stypvar(6)%rmissing_value    = -1000.
+      stypvar(6)%valid_min         = -1.
+      stypvar(6)%valid_max         = 1.
+      stypvar(6)%clong_name        = 'vertical saline gradient'
+      stypvar(6)%cshort_name       = 'vovegrads'
+      stypvar(6)%conline_operation = 'N/A'
+
+      ! create output fileset
+      ncout = create      (cf_out, cf_tfil, npiglo, npjglo, npk       )
+      ierr  = createvar   (ncout,  stypvar, jp_varout, ipk, id_varout )
+      ierr  = putheadervar(ncout,  cf_tfil, npiglo, npjglo, npk       )
+
+   END SUBROUTINE CreateOutput
+
+END PROGRAM cdfgradT
diff --git a/cdfhdy.f90 b/src/cdfhdy.f90
similarity index 100%
rename from cdfhdy.f90
rename to src/cdfhdy.f90
diff --git a/cdfhdy3d.f90 b/src/cdfhdy3d.f90
similarity index 100%
rename from cdfhdy3d.f90
rename to src/cdfhdy3d.f90
diff --git a/src/cdfheatc.f90 b/src/cdfheatc.f90
new file mode 100644
index 0000000..4ebe806
--- /dev/null
+++ b/src/cdfheatc.f90
@@ -0,0 +1,298 @@
+PROGRAM cdfheatc
+  !!======================================================================
+  !!                     ***  PROGRAM  cdfheatc  ***
+  !!=====================================================================
+  !!  ** Purpose : Compute the heat content of the ocean : 1 single value
+  !!
+  !!  ** Method  : compute the sum ( rho cp T  * e1t *e2t * e3t * tmask )
+  !!
+  !! History : 2.1  : 03/2006  : J.M. Molines : Original code
+  !!           3.0  : 01/2011  : J.M. Molines : Doctor norm + Lic.
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id$
+  !! Copyright (c) 2011, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4), PARAMETER                :: jp_hc3d=1, jp_hc2d=2 , jp_hcvol=3
+  INTEGER(KIND=4)                           :: jk, jt              ! dummy loop index
+  INTEGER(KIND=4)                           :: ik                  ! working integer
+  INTEGER(KIND=4)                           :: ierr                ! working integer
+  INTEGER(KIND=4)                           :: iimin=0, iimax=0    ! domain limitation for computation
+  INTEGER(KIND=4)                           :: ijmin=0, ijmax=0    ! domain limitation for computation
+  INTEGER(KIND=4)                           :: ikmin=0, ikmax=0    ! domain limitation for computation
+  INTEGER(KIND=4)                           :: mxloption=0         ! mixed layer option    
+  INTEGER(KIND=4)                           :: narg, iargc, ijarg  ! command line 
+  INTEGER(KIND=4)                           :: npiglo, npjglo      ! size of the domain
+  INTEGER(KIND=4)                           :: npk, npkk,npt       ! size of the domain
+  INTEGER(KIND=4)                           :: nvpk                ! vertical levels in working variable
+  INTEGER(KIND=4)                           :: ncout
+  INTEGER(KIND=4), DIMENSION(:),  ALLOCATABLE  :: ipk, id_varout   ! for output variables
+
+  REAL(KIND=4), PARAMETER                   :: pprho0=1020.        ! water density (kg/m3)
+  REAL(KIND=4), PARAMETER                   :: ppcp=4000.          ! calorific capacity (J/kg/m3)
+
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e1t, e2t            ! horizontal metrics
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e3t                 ! vertical metric
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: temp                ! temperature
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: tmask               ! tmask
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: rmxldep             ! mixed layer depth
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: gdepw               ! depth
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim                 ! time counter
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: e31d                ! vertical metrics in case of full step
+
+  REAL(KIND=8)                              :: dvol                ! 3D volume of the ocean
+  REAL(KIND=8)                              :: dsum                ! weighted sum 3D
+  REAL(KIND=8)                              :: dvol2d              ! volume of a layer
+  REAL(KIND=8)                              :: dsum2d              ! weigthed sum per layer
+  REAL(KIND=8)                              :: dsurf               ! surface of a layer
+  REAL(KIND=8), DIMENSION(1,1)              :: dl_dum              ! working pseudo array for nc output
+
+  TYPE(variable), DIMENSION(:),    ALLOCATABLE :: stypvar          ! structure for attributes
+
+  CHARACTER(LEN=256)                        :: cf_tfil             ! input gridT file
+  CHARACTER(LEN=256)                        :: cf_out='heatc.nc'   ! netcdf output file
+  CHARACTER(LEN=256)                        :: cldum               ! dummy character variable
+  CHARACTER(LEN=256)                        :: cv_msk='tmask'      ! variable for masking
+
+  LOGICAL                                   :: lfull=.FALSE.       ! flag for full step computation
+  LOGICAL                                   :: lchk                ! flag for missing files
+
+  ! NETCDF OUTPUT
+  !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  narg = iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage :  cdfheatc  -f T-file [-mxloption option] ...'
+     PRINT *,'     [-zoom imin imax jmin jmax kmin kmax] [-full] [-o OUT-file]'
+     PRINT *,'     [-M MSK-file VAR-mask ]'
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'        Computes the heat content in the specified 3D area (Joules)'
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       -f T-file : name of the input file with temperature (and MLD if needed).'
+     PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'       [-zoom imin imax jmin jmax kmin kmax] : limit of a sub domain where'
+     PRINT *,'                      the heat content will be calculated.'
+     PRINT *,'                   - if imin = 0 then ALL i are taken'
+     PRINT *,'                   - if jmin = 0 then ALL j are taken'
+     PRINT *,'                   - if kmin = 0 then ALL k are taken'
+     PRINT *,'       [-full ] : assume full step model output instead of default'
+     PRINT *,'                  partial steps.'
+     PRINT *,'       [-mxloption option]: option= 1 : compute only in the mixed layer,'
+     PRINT *,'                            option=-1 : exclude mixed layer in the computation'
+     PRINT *,'                            option= 0 : [Default], do not take care of mxl.'
+     PRINT *,'       [-o OUT-file ] : specify netcdf output filename instead of ',TRIM(cf_out)
+     PRINT *,'       [-M MSK-file VAR-mask] : Allow the use of a non standard mask file '
+     PRINT *,'              with VAR-mask, instead of ',TRIM(cn_fmsk),' and ',TRIM(cv_msk) 
+     PRINT *,'              This option is a usefull alternative to -zoom option, when the '
+     PRINT *,'              area of interest is not ''box-like'' '
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'       Files ',TRIM(cn_fhgr),', ',TRIM(cn_fzgr),' and ',TRIM(cn_fmsk) 
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file : heatc.nc unless -o option is used.'
+     PRINT *,'              variables: heatc3d (Joules)'
+     PRINT *,'                       : heatc(dep) (Joules) '
+     PRINT *,'                       : heatc3dpervol (Joules/m3) '
+     PRINT *,'       Standard output'
+     PRINT *,'       '
+     PRINT *,'      SEE ALSO: '
+     PRINT *,'          cdfpolymask '
+     STOP
+  ENDIF
+
+  ijarg = 1 
+  DO WHILE ( ijarg <= narg ) 
+     CALL getarg ( ijarg, cldum) ; ijarg = ijarg + 1
+     SELECT CASE ( cldum )
+     CASE ( '-f'    ) ; CALL getarg ( ijarg, cf_tfil) ; ijarg = ijarg + 1
+     CASE ( '-full' ) ; lfull = .true.
+     CASE ( '-mxloption' ) ; CALL getarg ( ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) mxloption
+     CASE ( '-o   ' ) ; CALL getarg ( ijarg, cf_out)    ; ijarg = ijarg + 1 
+     CASE ( '-zoom' )   
+        CALL getarg ( ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) iimin
+        CALL getarg ( ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) iimax
+        CALL getarg ( ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) ijmin
+        CALL getarg ( ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) ijmax
+        CALL getarg ( ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) ikmin
+        CALL getarg ( ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) ikmax
+     CASE ( '-M' )   
+        CALL getarg ( ijarg, cn_fmsk) ; ijarg = ijarg + 1 
+        CALL getarg ( ijarg, cv_msk ) ; ijarg = ijarg + 1
+     CASE DEFAULT
+        PRINT *,' A single argument is considered as a T-file'
+        CALL getarg ( ijarg, cf_tfil) ; ijarg = ijarg + 1 
+     END SELECT
+  END DO
+
+  lchk = chkfile(cn_fhgr)
+  lchk = chkfile(cn_fzgr) .OR. lchk
+  lchk = chkfile(cn_fmsk) .OR. lchk
+  lchk = chkfile(cf_tfil) .OR. lchk
+  IF ( lchk ) STOP ! missing files
+
+  npiglo = getdim (cf_tfil,cn_x)
+  npjglo = getdim (cf_tfil,cn_y)
+  npk    = getdim (cf_tfil,cn_z)
+  npt    = getdim (cf_tfil,cn_t)
+
+  npkk=npk
+
+  IF (iimin /= 0 ) THEN ; npiglo = iimax - iimin + 1;  ELSE ; iimin=1 ; ENDIF
+  IF (ijmin /= 0 ) THEN ; npjglo = ijmax - ijmin + 1;  ELSE ; ijmin=1 ; ENDIF
+  IF (ikmin /= 0 ) THEN ; npkk   = ikmax - ikmin + 1;  ELSE ; ikmin=1 ; ikmax=npk ; ENDIF
+
+  nvpk   = getvdim(cf_tfil,cn_votemper)
+  IF (nvpk == 2 ) nvpk = 1
+  IF (nvpk == 3 ) nvpk = npkk
+
+  PRINT *, 'npiglo = ', npiglo
+  PRINT *, 'npjglo = ', npjglo
+  PRINT *, 'npk    = ', npk
+  PRINT *, 'npt    = ', npt
+  PRINT *, 'nvpk   = ', nvpk
+
+  ! Allocate arrays
+  PRINT *, 'Allocate TMASK'
+  ALLOCATE ( tmask(npiglo,npjglo))
+  PRINT *, 'Allocate temp'
+  ALLOCATE ( temp (npiglo,npjglo))
+  PRINT *, 'Allocate e1t'
+  ALLOCATE ( e1t  (npiglo,npjglo), e2t(npiglo,npjglo), e3t(npiglo,npjglo))
+
+  IF (mxloption /= 0) THEN
+      PRINT *, 'Allocate rmxldep'
+      ALLOCATE ( rmxldep(npiglo,npjglo))
+  ENDIF
+
+  PRINT *, 'Allocate gdepw'
+  ALLOCATE ( gdepw(npk), tim(npt))
+  IF ( lfull ) ALLOCATE ( e31d(npk))
+
+  e1t(:,:) = getvar(cn_fhgr, cn_ve1t, 1, npiglo, npjglo, kimin=iimin, kjmin=ijmin)
+  e2t(:,:) = getvar(cn_fhgr, cn_ve2t, 1, npiglo, npjglo, kimin=iimin, kjmin=ijmin)
+  gdepw(:) = getvare3(cn_fzgr, cn_gdepw,  npk)
+  tim  (:) = getvare3(cf_tfil, cn_vtimec, npt)
+  
+  IF ( lfull ) e31d(:) = getvare3(cn_fzgr, cn_ve3t, npk)
+
+  CALL CreateOutput
+
+  DO jt=1,npt
+     dvol = 0.d0
+     dsum = 0.d0
+     PRINT * ,'TIME : ', tim(jt)
+     IF (mxloption /= 0) rmxldep(:,:) = getvar(cf_tfil, cn_somxl010, 1, npiglo, npjglo, ktime=jt)
+
+     DO jk = 1,nvpk
+        ik = jk + ikmin -1
+        ! Get temperatures temp at ik
+        temp( :,:)   = getvar(cf_tfil, cn_votemper, ik, npiglo, npjglo, kimin=iimin, kjmin=ijmin, ktime=jt)
+        tmask(:,:)   = getvar(cn_fmsk, cv_msk,      ik, npiglo, npjglo, kimin=iimin, kjmin=ijmin          )           
+
+        ! get e3t at level ik ( ps...)
+        IF ( lfull ) THEN
+           e3t(:,:) = e31d(ik)
+        ELSE
+           e3t(:,:) = getvar(cn_fzgr, 'e3t_ps', ik, npiglo, npjglo, kimin=iimin, kjmin=ijmin, ldiom=.TRUE.)
+        ENDIF
+        
+        SELECT CASE ( mxloption ) 
+         CASE ( 1 ) 
+            e3t(:,:) = MAX ( 0., MIN( e3t,rmxldep-gdepw(ik) ) )
+         CASE ( -1 )
+            e3t(:,:) = MIN ( e3t, MAX( 0.,gdepw(ik)+e3t(:,:)-rmxldep ) )
+         END SELECT
+
+        dsurf  = sum(e1t * e2t       * tmask)
+        dvol2d = sum(e1t * e2t * e3t * tmask)
+        dvol   = dvol + dvol2d
+
+        dsum2d = sum(e1t * e2t * e3t * temp * tmask)
+        dsum   = dsum + dsum2d
+
+        IF (dvol2d /= 0 )THEN
+           PRINT *, ' Heat Content  at level ',ik,'(',gdepw(ik),' m) ',pprho0*ppcp*dsum2d, 'surface = ',dsurf/1.e6,' km^2'
+        ELSE
+           PRINT *, ' No points in the water at level ',ik,'(',gdepw(ik),' m) '
+        ENDIF
+        dl_dum(1,1) = pprho0*ppcp*dsum2d
+        ierr = putvar(ncout, id_varout(jp_hc2d), dl_dum(:,:),jk, 1, 1, ktime=jt )
+
+     END DO
+     
+     PRINT * ,' Total Heat content        : ', pprho0*ppcp*dsum ,' Joules'
+     PRINT * ,' Total Heat content/volume : ', pprho0*ppcp*dsum/dvol ,' Joules/m3 '
+     dl_dum(1,1)=pprho0*ppcp*dsum
+     ierr = putvar(ncout, id_varout(jp_hc3d), dl_dum(:,:),1, 1, 1, ktime=jt )
+     dl_dum(1,1)=dl_dum(1,1)/dvol
+     ierr = putvar(ncout, id_varout(jp_hcvol), dl_dum(:,:),1, 1, 1, ktime=jt )
+  END DO
+  ierr = closeout(ncout )
+CONTAINS
+  SUBROUTINE CreateOutput
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE CreateOutput  ***
+    !!
+    !! ** Purpose :  Create the netcdf outputfile 
+    !!
+    !!----------------------------------------------------------------------
+    ! so far in cdfheatc, only 4 variables willbe output.
+    ! indeed 4 scalar but that will be considered as (x,y,t) ie (1,1,t)
+    INTEGER(KIND=4) :: ivar=3, ierr
+    REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zdumlon, zdumlat
+    !!----------------------------------------------------------------------
+    ALLOCATE(stypvar(ivar) )
+    ALLOCATE(    ipk(ivar), id_varout(ivar) )
+    ALLOCATE( zdumlon(1,1), zdumlat(1,1) )
+    zdumlon(:,:) = 0.
+    zdumlat(:,:) = 0.
+    ipk(:)= 1 
+    ! define new variables for output 
+
+    stypvar%scale_factor      = 1.
+    stypvar%add_offset        = 0.
+    stypvar%savelog10         = 0.
+    stypvar%conline_operation = 'N/A'
+    stypvar%caxis             = 'T'
+    stypvar%cprecision        = 'r8'
+
+    stypvar(jp_hc3d)%cname          = 'heatc3d'
+    stypvar(jp_hc3d)%cunits         = 'Joules'
+    stypvar(jp_hc3d)%clong_name     = 'Total Heat Content'
+    stypvar(jp_hc3d)%cshort_name    = 'heatc3d'
+
+    stypvar(jp_hcvol)%cname          = 'heatc3dpervol'
+    stypvar(jp_hcvol)%cunits         = 'Joules/m3'
+    stypvar(jp_hcvol)%clong_name     = 'Total Heat Content per unit volume'
+    stypvar(jp_hcvol)%cshort_name    = 'heatc3dpervol'
+
+    ipk(jp_hc2d) = npkk
+    stypvar(jp_hc2d)%cname          = 'heatc2d'
+    stypvar(jp_hc2d)%cunits         = 'Joules'
+    stypvar(jp_hc2d)%clong_name     = 'Heat Content at each selected level'
+    stypvar(jp_hc2d)%cshort_name    = 'heatc2d'
+
+    ncout =  create     (cf_out, 'none',  1,      1, npkk,   cdep='depthw' )
+    ierr  = createvar   (ncout,  stypvar, ivar, ipk, id_varout             )
+    ierr  = putheadervar(ncout,  cf_tfil, 1,      1, npkk,                 &
+                  &         pnavlon=zdumlon, pnavlat=zdumlat,              &
+                  &         pdep=gdepw(ikmin:ikmax),                       &
+                  &         cdep='depthw'                                  )
+    tim(:)= putvar1d(ncout,  tim,       npt, 'T')
+
+    DEALLOCATE( zdumlon, zdumlat)
+    
+  END SUBROUTINE CreateOutput
+
+END PROGRAM cdfheatc
diff --git a/cdfhflx.f90 b/src/cdfhflx.f90
similarity index 100%
rename from cdfhflx.f90
rename to src/cdfhflx.f90
diff --git a/src/cdfhgradb.f90 b/src/cdfhgradb.f90
new file mode 100644
index 0000000..e3df3d2
--- /dev/null
+++ b/src/cdfhgradb.f90
@@ -0,0 +1,273 @@
+PROGRAM cdfhgradb
+   !!======================================================================
+   !!                     ***  PROGRAM  cdfhgradb ***
+   !!=====================================================================
+   !!  ** Purpose : Compute the norm of the lateral buoyancy gradient.
+   !!
+   !!  ** Method  :
+   !!
+   !! History : 3.0  : 08/2015  : J. Le Sommer (from cdfgradT)
+   !!----------------------------------------------------------------------
+   !!----------------------------------------------------------------------
+   !!   routines      : description
+   !!   CreateOutput  :  perform all the stuff linked with output file 
+   !!----------------------------------------------------------------------
+   USE cdfio
+   USE eos
+   USE modcdfnames
+   !!----------------------------------------------------------------------
+   !! CDFTOOLS_3.0 , MEOM 2015
+   !! $Id$
+   !! Copyright (c) 2012, J.-M. Molines
+   !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+   !!----------------------------------------------------------------------
+   IMPLICIT NONE
+
+   INTEGER(KIND=4), PARAMETER                  :: jp_varout = 1     ! number of output variables
+   INTEGER(KIND=4)                             :: jk, jt            ! dummy loop index
+   INTEGER(KIND=4)                             :: ji, jj, jlev      ! dummy loop index
+   INTEGER(KIND=4)                             :: narg, ijarg, iargc! command line
+   INTEGER(KIND=4)                             :: npiglo, npjglo    ! size of the domain
+   INTEGER(KIND=4)                             :: npk, npkk,  npt   ! size of the domain
+   INTEGER(KIND=4)                             :: ncout             ! ncid of output variable
+   INTEGER(KIND=4)                             :: ierr              ! error status
+   INTEGER(KIND=4), DIMENSION(jp_varout)       :: ipk, id_varout    ! output variable
+
+   REAL(KIND=4), DIMENSION(:),     ALLOCATABLE :: tim               ! time variable
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: umask, vmask, tmask ! relevant mask
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: e1u, e2v          ! metrics
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: zt, zs            ! Temperature Salinity on 2 levels
+   REAL(KIND=4), DIMENSION(:),     ALLOCATABLE :: gdept             ! depth of Tlevels
+   REAL(KIND=4)                                :: zdep              ! temporary scalar
+
+   REAL(KIND=8)                                :: dgrav=9.81d0
+
+   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dgradt_xu, dgradt_yv! Temperature gradient, native grid
+   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dgrads_xu, dgrads_yv! Salinity gradient, native grid
+
+   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dgradt_xt, dgradt_yt! Temperature gradient, t-point
+   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dgrads_xt, dgrads_yt! Salinity gradient, t-point
+
+   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dgradb_xt, dgradb_yt ! Buyoyancy gradient, t-point
+   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dgradb              ! norm of the buyoyancy gradient, t-point
+
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: zalbet, zbeta         ! for alpha and beta
+
+   CHARACTER(LEN=256)                         :: cf_tfil             ! input file name for T and S
+   CHARACTER(LEN=256)                         :: cf_sfil             ! input file name for S (optional)
+   CHARACTER(LEN=256)                         :: cf_out = 'hgradb_gridT.nc' ! output file name
+   CHARACTER(LEN=256)                         :: cldum               ! dummy character variable
+   CHARACTER(LEN=256)                         :: cv_sal              ! salinity name in netcdf
+   CHARACTER(LEN=256)                         :: cv_tem              ! temperature name in netcdf
+
+   TYPE(variable), DIMENSION(jp_varout)       :: stypvar             ! output data structure
+
+   LOGICAL                                    :: lchk = .FALSE.      ! flag for missing files
+   LOGICAL                                    :: lnc4 = .FALSE.      ! flag for netcdf4 output with chunking and deflation
+
+   !!----------------------------------------------------------------------
+   CALL ReadCdfNames()
+
+   narg= iargc()
+   IF ( narg == 0 ) THEN
+      PRINT *,' usage : cdfhgradb -t T-file [-s S-file] [-nc4 ] [-o OUT-file] ...'
+      PRINT *,'                   ...  [-sal SAL-name]  [-tem TEMP-name] '
+      PRINT *,'      '
+      PRINT *,'     PURPOSE :'
+      PRINT *,'        Compute the norm of the horizontal buoyancy gradient.'
+      PRINT *,'      Results are saved at T points.'
+      PRINT *,'      '
+      PRINT *,'     ARGUMENTS :'
+      PRINT *,'       -t T-file : File with ',TRIM(cn_votemper),' and ',TRIM(cn_vosaline),' variables' 
+      PRINT *,'           If ',TRIM(cn_vosaline),' not in T-file use -s option.'
+      PRINT *,'          Note that salinity and/or temperature variables name can be changed'
+      PRINT *,'          with -sal and/or -tem options, respectively.'
+      PRINT *,'      '
+      PRINT *,'     OPTIONS :'
+      PRINT *,'      [-s S-file ] : File with ',TRIM(cn_vosaline),' variable if not in T file'
+      PRINT *,'      [-nc4      ] : use netcdf4 chunking and deflation on output '
+      PRINT *,'      [-o output file] : specify the name of output file instead of '
+      PRINT *,'                default name ',TRIM(cf_out)
+      PRINT *,'      [-sal SAL-name] : specify the name of salinity variable'
+      PRINT *,'      [-tem TEM-name] : specify the name of temperature variable'
+      PRINT *,'      '
+      PRINT *,'     REQUIRED FILES :'
+      PRINT *,'       ', TRIM(cn_fhgr),' ',TRIM(cn_fmsk),' and ',TRIM(cn_fzgr)
+      PRINT *,'      '
+      PRINT *,'     OUTPUT : '
+      PRINT *,'       netcdf file : ', TRIM(cf_out),' ( unless specified with -o option)' 
+      PRINT *,'         ',jp_varout,' variables : '
+      PRINT *,'              vohgradb: norm of the horizontal buoyancy gradient at t-point'
+      PRINT *,'      '
+      PRINT *,'     SEE ALSO :'
+      PRINT *,'        cdfbuoyflx  '
+      PRINT *,'      '
+      STOP
+   ENDIF
+
+   ijarg =1 
+   cv_sal=cn_vosaline
+   cv_tem=cn_votemper
+   DO WHILE ( ijarg <= narg )
+     CALL getarg (ijarg, cldum ) ; ijarg = ijarg + 1 
+     SELECT CASE ( cldum) 
+     CASE ( '-t '  ) ; CALL getarg (ijarg, cf_tfil ) ; ijarg = ijarg+1
+                          cf_sfil=cf_tfil
+     CASE ( '-s '  ) ; CALL getarg (ijarg, cf_sfil ) ; ijarg = ijarg+1
+     CASE ( '-nc4 ') ; lnc4 = .TRUE.
+     CASE ( '-o'   ) ; CALL getarg (ijarg, cf_out ) ; ijarg = ijarg+1
+     CASE ( '-sal' ) ; CALL getarg (ijarg, cv_sal ) ; ijarg = ijarg+1
+     CASE ( '-tem' ) ; CALL getarg (ijarg, cv_tem ) ; ijarg = ijarg+1
+     CASE DEFAULT
+       PRINT *, 'Option ',TRIM(cldum),' not understood !'
+       PRINT *, 'Check usage with cdfhgradb (no argument).'
+       STOP
+     END SELECT
+   ENDDO
+
+   lchk = ( lchk .OR. chkfile(cf_tfil) )
+   lchk = ( lchk .OR. chkfile(cf_sfil) )
+   lchk = ( lchk .OR. chkfile(cn_fhgr) )
+   lchk = ( lchk .OR. chkfile(cn_fzgr) )
+   lchk = ( lchk .OR. chkfile(cn_fmsk) )
+   IF (lchk ) STOP ! missing file
+
+   npiglo = getdim (cf_tfil, cn_x)
+   npjglo = getdim (cf_tfil, cn_y)
+   npk    = getdim (cf_tfil, cn_z)
+   npt    = getdim (cf_tfil, cn_t)
+
+   PRINT *, 'npiglo = ', npiglo
+   PRINT *, 'npjglo = ', npjglo
+   PRINT *, 'npk    = ', npk
+   PRINT *, 'npt    = ', npt
+
+   npkk=npk
+   IF ( npk == 0 ) npkk = 1
+
+   !!  Allocate arrays
+   ALLOCATE (tim(npt) )
+   ALLOCATE (gdept(npkk) )
+   ALLOCATE (e1u  (npiglo,npjglo), e2v  (npiglo,npjglo) )
+   ALLOCATE (umask(npiglo,npjglo), vmask(npiglo,npjglo), tmask(npiglo,npjglo))
+   ALLOCATE (zt   (npiglo,npjglo), zs (npiglo,npjglo))
+   ALLOCATE ( zalbet(npiglo,npjglo), zbeta(npiglo, npjglo) )
+   ALLOCATE (dgradt_xu(npiglo,npjglo), dgradt_yv(npiglo,npjglo))
+   ALLOCATE (dgrads_xu(npiglo,npjglo), dgrads_yv(npiglo,npjglo))
+   ALLOCATE (dgradt_xt(npiglo,npjglo), dgradt_yt(npiglo,npjglo))
+   ALLOCATE (dgrads_xt(npiglo,npjglo), dgrads_yt(npiglo,npjglo))
+   ALLOCATE (dgradb_xt(npiglo,npjglo), dgradb_yt(npiglo,npjglo))
+   ALLOCATE (dgradb(npiglo,npjglo))
+
+   CALL CreateOutput
+
+   tim  = getvar1d(cf_tfil, cn_vtimec, npt     )
+   ierr = putvar1d(ncout,  tim,        npt, 'T')
+
+   e1u =  getvar(cn_fhgr, cn_ve1u, 1, npiglo, npjglo)
+   e2v =  getvar(cn_fhgr, cn_ve2v, 1, npiglo, npjglo)
+   gdept(:)    = getvare3(cn_fzgr, cn_gdept, npkk )
+
+   DO jt = 1,npt
+      DO jk = 1, npkk
+
+         PRINT *,'level ',jk
+         zdep = gdept(jk)
+
+         ! read files
+         zt(:,:) = getvar(cf_tfil, cv_tem, jk,   npiglo, npjglo, ktime=jt)
+         zs(:,:) = getvar(cf_sfil, cv_sal, jk,   npiglo, npjglo, ktime=jt)
+
+         umask(:,:) = getvar(cn_fmsk, 'umask' , jk, npiglo, npjglo )
+         vmask(:,:) = getvar(cn_fmsk, 'vmask' , jk, npiglo, npjglo )
+         tmask(:,:) = getvar(cn_fmsk, 'tmask' , jk, npiglo, npjglo )
+
+         ! zonal grad located at U point at current level
+         dgradt_xu(:,:) = 0.d0
+         dgradt_xu(1:npiglo-1,:) = 1.d0 / e1u(1:npiglo-1,:) * &
+              &                 ( zt(2:npiglo,:) - zt(1:npiglo-1,:) ) * umask(1:npiglo-1,:)
+         dgrads_xu(:,:) = 0.d0
+         dgrads_xu(1:npiglo-1,:) = 1.d0 / e1u(1:npiglo-1,:) * &
+              &                 ( zs(2:npiglo,:) - zs(1:npiglo-1,:) ) * umask(1:npiglo-1,:)
+
+         ! meridional grad located at V point at current level
+         dgradt_yv(:,:) = 0.d0
+         dgradt_yv(:,1:npjglo-1) = 1.d0 / e2v(:,1:npjglo-1) * &
+              &                 ( zt(:,2:npjglo) - zt(:,1:npjglo-1) ) * vmask(:,1:npjglo-1)
+         dgrads_yv(:,:) = 0.d0
+         dgrads_yv(:,1:npjglo-1) = 1.d0 / e2v(:,1:npjglo-1) * &
+              &                 ( zs(:,2:npjglo) - zs(:,1:npjglo-1) ) * vmask(:,1:npjglo-1)
+
+         ! get temperature and salinity gradients at t-point 
+         dgradt_xt(:,:) = 0.d0
+         dgradt_yt(:,:) = 0.d0
+         dgrads_xt(:,:) = 0.d0
+         dgrads_yt(:,:) = 0.d0
+
+         DO ji=2,npiglo
+             DO jj=2,npjglo
+               dgradt_xt(ji,jj) = 0.5*(dgradt_xu(ji-1,jj)+dgradt_xu(ji,jj))
+               dgrads_xt(ji,jj) = 0.5*(dgrads_xu(ji-1,jj)+dgrads_xu(ji,jj))
+               dgradt_yt(ji,jj) = 0.5*(dgradt_yv(ji,jj-1)+dgradt_yv(ji,jj))
+               dgrads_yt(ji,jj) = 0.5*(dgrads_yv(ji,jj-1)+dgrads_yv(ji,jj))
+             ENDDO
+         ENDDO
+         
+         !DO ji=1,npiglo
+         !    DO jj=npjglo,2 -1
+         !      dgradt_yt(ji,jj) = 0.5*(dgradt_yv(ji,jj-1)+dgradt_yv(ji,jj))
+         !      dgrads_yt(ji,jj) = 0.5*(dgrads_yv(ji,jj-1)+dgrads_yv(ji,jj))
+         !    ENDDO
+         ! ENDDO
+
+         ! compute alpha and beta at t-point
+         zalbet(:,:) = albet ( zt, zs, zdep, npiglo, npjglo) ! not exact for partial-step level
+         zbeta (:,:) = beta  ( zt, zs, zdep, npiglo, npjglo) ! 
+
+         ! compute the buoyancy gradients at t-point
+         dgradb_xt(:,:) = zbeta(:,:) * ( zalbet(:,:) * dgradt_xt(:,:) - dgrads_xt(:,:) ) * tmask(:,:)
+         dgradb_yt(:,:) = zbeta(:,:) * ( zalbet(:,:) * dgradt_yt(:,:) - dgrads_yt(:,:) ) * tmask(:,:)
+
+         ! get the norm of the buoyancy gradients at t-point
+         dgradb(:,:) = dgrav * SQRT( dgradb_xt(:,:) * dgradb_xt(:,:) + dgradb_yt(:,:) * dgradb_yt(:,:) )
+
+         ! write
+         ierr = putvar(ncout, id_varout(1), REAL(dgradb), jk, npiglo, npjglo, ktime=jt)
+      END DO
+   END DO
+
+   ierr = closeout(ncout)
+
+CONTAINS
+   SUBROUTINE CreateOutput
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE CreateOutput  ***
+      !!
+      !! ** Purpose :  Set up all things required for the output file, create
+      !!               the file and write the header part. 
+      !!
+      !! ** Method  :  Use global module variables 
+      !!
+      !!----------------------------------------------------------------------
+      ipk(:) = npkk  !  3D
+
+
+      stypvar(1)%cname             = 'vohgradb'
+      stypvar(1)%cunits            = 's^{-2}'
+      stypvar(1)%rmissing_value    = -1000.
+      stypvar(1)%valid_min         = -1.
+      stypvar(1)%valid_max         = 1.
+      stypvar(1)%clong_name        = 'Horizontal gradient of buoyancy.'
+      stypvar(1)%cshort_name       = 'vohgradb'
+      stypvar(1)%conline_operation = 'N/A'
+      stypvar(1)%ichunk            = (/npiglo, MAX(1,npjglo/30), 1, 1 /)
+
+
+      ! create output fileset
+      ncout = create      (cf_out, cf_tfil, npiglo, npjglo, npk,       ld_nc4=lnc4    )
+      ierr  = createvar   (ncout,  stypvar, jp_varout, ipk, id_varout, ld_nc4=lnc4    )
+      ierr  = putheadervar(ncout,  cf_tfil, npiglo, npjglo, npk       )
+
+   END SUBROUTINE CreateOutput
+
+END PROGRAM cdfhgradb
diff --git a/src/cdficb_clim.f90 b/src/cdficb_clim.f90
new file mode 100644
index 0000000..bea9885
--- /dev/null
+++ b/src/cdficb_clim.f90
@@ -0,0 +1,174 @@
+PROGRAM cdficb_clim
+  !!======================================================================
+  !!                     ***  PROGRAM  cdficb_clim  ***
+  !!=====================================================================
+  !!  ** Purpose : Compute the iceberg mass and melt
+  !!
+  !!  ** Method  : Use the icb files for input and determine the
+  !!
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)                            :: jk, jj, jt, ji       ! dummy loop index
+  INTEGER(KIND=4)                            :: ierr                 ! working integer
+  INTEGER(KIND=4)                            :: narg, iargc          ! command line 
+  INTEGER(KIND=4)                            :: npiglo, npjglo, npt, numFiles  ! size of the domain
+  INTEGER(KIND=4)                            :: nvpk                 ! vertical levels in working variable
+  INTEGER(KIND=4)                            :: nperio = 4           ! boundary condition ( periodic, north fold)
+  INTEGER(KIND=4)                            :: ikx, iky, ikz=0      ! dims of netcdf output file
+  INTEGER(KIND=4)                            :: nboutput=2           ! number of values to write in cdf output
+  INTEGER(KIND=4)                            :: ncout                ! for netcdf output
+  INTEGER(KIND=4), DIMENSION(:), ALLOCATABLE :: ipk, id_varout, itimeVar
+
+  REAL(KIND=4), DIMENSION(:,:),  ALLOCATABLE :: e1, e2               ! metrics
+  REAL(KIND=4), DIMENSION(:,:),  ALLOCATABLE :: tmask, ff            ! npiglo x npjglo
+  REAL(KIND=4), DIMENSION(:,:),  ALLOCATABLE :: ricbmass, ricbmelt   ! icbmass icbmelt
+  REAL(KIND=4), DIMENSION(:,:),  ALLOCATABLE :: rdumlon, rdumlat     ! dummy lon lat for output
+  REAL(KIND=4), DIMENSION(:),    ALLOCATABLE :: tim                  ! time counter
+
+  TYPE(variable), DIMENSION(:),  ALLOCATABLE :: stypvar              ! structure of output
+  !
+  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cf_icb            ! input icb file
+  CHARACTER(LEN=256)                         :: cf_out='icbdiags.nc' ! output file
+  CHARACTER(LEN=256)                         :: cldum                ! dummy string
+  !
+  LOGICAL                                    :: lchk  = .false.      ! missing file flag
+  !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  narg = iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage : cdficb_clim 12-ICB-monthly-means-files'
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'        Compute the 2D field of icb mass and icb melt.'
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       ICE-file : netcdf icb file' 
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'        ',TRIM(cn_fhgr),' and ',TRIM(cn_fmsk)
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file : ', TRIM(cf_out) 
+     PRINT *,'         variables : Mass  (Kg/m2 )'
+     PRINT *,'                     Melt  (Kg/m2/s )'
+     STOP
+  ENDIF
+
+  CALL getarg(1,cldum)
+  READ(cldum,*) numFiles
+  
+  IF (numFiles < 12) STOP
+
+  ALLOCATE(cf_icb(numFiles))
+
+  DO ji= 1, numFiles
+        CALL getarg(ji+1,cf_icb(ji))
+        lchk = lchk .OR. chkfile(cf_icb(ji))
+  END DO
+
+
+  lchk = lchk .OR. chkfile(cn_fhgr) 
+  lchk = lchk .OR. chkfile(cn_fmsk) 
+
+  IF ( lchk ) STOP ! missing file
+
+  npiglo = getdim (cf_icb(1),cn_x)
+  npjglo = getdim (cf_icb(1),cn_y)
+  npt    = 12
+  ikx = npiglo
+  iky = npjglo
+
+  ALLOCATE ( tmask(npiglo,npjglo) ,ff(npiglo,npjglo) )
+  ALLOCATE ( ricbmass(npiglo,npjglo) )
+  ALLOCATE ( ricbmelt(npiglo,npjglo) )
+  ALLOCATE ( e1(npiglo,npjglo),e2(npiglo,npjglo) )
+  ALLOCATE ( tim(npt),itimeVar(npt) )
+ 
+  itimeVar = (/(ji,ji=1,12)/)  
+
+  ALLOCATE ( stypvar(nboutput), ipk(nboutput), id_varout(nboutput) )
+  ALLOCATE ( rdumlon(1,1), rdumlat(1,1) )
+
+  rdumlon(:,:) = 0.
+  rdumlat(:,:) = 0.
+
+  ipk(:) = 1
+
+  ! define new variables for output 
+  stypvar%scale_factor      = 1.
+  stypvar%add_offset        = 0.
+  stypvar%savelog10         = 0.
+  stypvar%conline_operation = 'N/A'
+  stypvar%caxis             = 'T'
+
+  stypvar(1)%cname          = 'Mass'
+  stypvar(1)%cunits         = 'Kg/m2'
+  stypvar(1)%clong_name     = 'Icb mass per unit of area'
+  stypvar(1)%cshort_name    = 'Mass'
+
+  stypvar(2)%cname          = 'Melt'
+  stypvar(2)%cunits         = 'Kg/m2/s'
+  stypvar(2)%clong_name     = 'Icb melt flux'
+  stypvar(2)%cshort_name    = 'Melt'
+
+
+  e1(:,:) = getvar(cn_fhgr, cn_ve1t,  1, npiglo, npjglo)
+  e2(:,:) = getvar(cn_fhgr, cn_ve2t,  1, npiglo, npjglo)
+  ff(:,:) = getvar(cn_fhgr, cn_gphit, 1, npiglo, npjglo) ! only the sign of ff is important
+
+  tmask(:,:)=getvar(cn_fmsk,'tmask',1,npiglo,npjglo)
+  SELECT CASE (nperio)
+  CASE (0) ! closed boundaries
+     ! nothing to do
+  CASE (4) ! ORCA025 type boundary
+     tmask(1:2,:)=0.
+     tmask(:,npjglo)=0.
+     tmask(npiglo/2+1:npiglo,npjglo-1)= 0.
+  CASE (6)
+     tmask(1:2,:)=0.
+     tmask(:,npjglo)=0.
+  CASE DEFAULT
+     PRINT *,' Nperio=', nperio,' not yet coded'
+     STOP
+  END SELECT
+
+  itimeVar = (/(ji,ji=1,12)/)
+  ! Check variable
+  IF (chkvar(cf_icb(1), cn_iicbmass)) THEN
+     cn_iicbmass='missing'
+     PRINT *,'' 
+     PRINT *,' WARNING, ICEBERG MASS IS SET TO 0. '
+     PRINT *,' '
+  END IF
+
+  !
+  DO jt = 1, npt
+     IF (TRIM(cn_iicbmass) /= 'missing') ricbmass(:,:) = getvar(cf_icb(jt), cn_iicbmass, 1, npiglo, npjglo, ktime=1)
+     ricbmelt(:,:) = getvar(cf_icb(jt), cn_iicbmelt, 1, npiglo, npjglo, ktime=1)
+
+    IF ( jt == 1 ) THEN
+         ! create output fileset
+        ncout = create      (cf_out, 'none',  ikx,      iky, ikz,     cdep='depthw'                   )
+        ierr  = createvar   (ncout,  stypvar, nboutput, ipk, id_varout                                )
+        ierr  = putheadervar(ncout,  cf_icb(1), ikx,      iky, ikz)
+
+        tim   = getvar1d(cf_icb(1), cn_vtimec, npt     )
+        tim = (/(ji,ji=1,12)/)
+        ierr  = putvar1d(ncout,   tim,       npt, 'T')
+     ENDIF
+
+     ! netcdf output
+     !ierr = putvar0d(ncout,cn_vtimec,jt,ktime=jt) 
+     ierr = putvar(ncout,id_varout(1),REAL(ricbmass(:,:)),1,npiglo,npjglo, ktime=jt)
+     ierr = putvar(ncout,id_varout(2),REAL(ricbmelt(:,:)),1,npiglo,npjglo, ktime=jt)
+
+  END DO ! time loop
+  ierr = closeout(ncout)
+
+END PROGRAM cdficb_clim
diff --git a/src/cdficb_diags.f90 b/src/cdficb_diags.f90
new file mode 100644
index 0000000..f4d339f
--- /dev/null
+++ b/src/cdficb_diags.f90
@@ -0,0 +1,204 @@
+PROGRAM cdficb_diags
+  !!======================================================================
+  !!                     ***  PROGRAM  cdficb_diags  ***
+  !!=====================================================================
+  !!  ** Purpose : Compute the Ice volume, area and extend for each 
+  !!               hemisphere
+  !!
+  !!  ** Method  : Use the icemod files for input and determine the
+  !!               hemisphere with sign of the coriolis parameter.
+  !!
+  !! History : 3.0  : 01/2016  : N. Merino : Original code
+
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id: cdficb_diags.f90 759 2014-07-21 22:01:28Z molines $
+  !! Copyright (c) 2010, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)                            :: jk, jj, jt           ! dummy loop index
+  INTEGER(KIND=4)                            :: ierr                 ! working integer
+  INTEGER(KIND=4)                            :: narg, iargc          ! command line 
+  INTEGER(KIND=4)                            :: npiglo, npjglo, npt  ! size of the domain
+  INTEGER(KIND=4)                            :: nvpk                 ! vertical levels in working variable
+  INTEGER(KIND=4)                            :: nperio = 4           ! boundary condition ( periodic, north fold)
+  INTEGER(KIND=4)                            :: ikx=1, iky=1, ikz=0  ! dims of netcdf output file
+  INTEGER(KIND=4)                            :: nboutput=4           ! number of values to write in cdf output
+  INTEGER(KIND=4)                            :: ncout                ! for netcdf output
+  INTEGER(KIND=4), DIMENSION(:), ALLOCATABLE :: ipk, id_varout
+
+  REAL(KIND=4), DIMENSION(:,:),  ALLOCATABLE :: e1, e2               ! metrics
+  REAL(KIND=4), DIMENSION(:,:),  ALLOCATABLE :: tmask, ff            ! npiglo x npjglo
+  REAL(KIND=4), DIMENSION(:,:),  ALLOCATABLE :: ricbmass, ricbmelt ! thickness, leadfrac (concentration)
+  REAL(KIND=4), DIMENSION(:,:),  ALLOCATABLE :: rdumlon, rdumlat     ! dummy lon lat for output
+  REAL(KIND=4), DIMENSION(:),    ALLOCATABLE :: tim                  ! time counter
+
+  REAL(KIND=8)                               :: dmasss, dmelts        ! volume, area extend South hemisphere
+  REAL(KIND=8)                               :: dextends, dextends2  ! volume, area extend South hemisphere
+  REAL(KIND=8)                               :: dmassn, dmeltn        ! volume, area extend North hemisphere
+  REAL(KIND=8)                               :: dextendn, dextendn2  ! volume, area extend North hemisphere
+
+  TYPE(variable), DIMENSION(:),  ALLOCATABLE :: stypvar              ! structure of output
+  !
+  CHARACTER(LEN=256)                         :: cf_ifil              ! input ice file
+  CHARACTER(LEN=256)                         :: cf_out='icbdiags.nc' ! output file
+  CHARACTER(LEN=256)                         :: cldum                ! dummy string
+  !
+  LOGICAL                                    :: lchk  = .false.      ! missing file flag
+  LOGICAL                                    :: llim3 = .false.      ! LIM3 flag
+  !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  narg = iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage : cdficb_diags ICB-file  '
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'        Compute the spatially integrated icb mass and melt flux.'
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       ICB-file : a single netcdf icb file' 
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'        ',TRIM(cn_fhgr),' and ',TRIM(cn_fmsk)
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file : ', TRIM(cf_out) 
+     PRINT *,'         variables : [NS]Mass  (Kg )'
+     PRINT *,'                     [NS]Melt    (Kg/s )'
+     PRINT *,'               N = northern hemisphere'
+     PRINT *,'               S = southern hemisphere'
+     PRINT *,'       standard output'
+     STOP
+  ENDIF
+
+  CALL getarg (1, cf_ifil)
+
+  lchk = lchk .OR. chkfile(cn_fhgr) 
+  lchk = lchk .OR. chkfile(cn_fmsk) 
+  lchk = lchk .OR. chkfile(cf_ifil)
+
+  IF ( lchk ) STOP ! missing file
+
+  npiglo = getdim (cf_ifil,cn_x)
+  npjglo = getdim (cf_ifil,cn_y)
+  npt    = getdim (cf_ifil,cn_t)
+
+  ALLOCATE ( tmask(npiglo,npjglo) ,ff(npiglo,npjglo) )
+  ALLOCATE ( ricbmass(npiglo,npjglo) )
+  ALLOCATE ( ricbmelt(npiglo,npjglo) )
+  ALLOCATE ( e1(npiglo,npjglo),e2(npiglo,npjglo) )
+  ALLOCATE ( tim(npt) )
+
+  ALLOCATE ( stypvar(nboutput), ipk(nboutput), id_varout(nboutput) )
+  ALLOCATE ( rdumlon(1,1), rdumlat(1,1) )
+
+  rdumlon(:,:) = 0.
+  rdumlat(:,:) = 0.
+
+  ipk(:) = 1
+
+  ! define new variables for output 
+  stypvar%scale_factor      = 1.
+  stypvar%add_offset        = 0.
+  stypvar%savelog10         = 0.
+  stypvar%conline_operation = 'N/A'
+  stypvar%caxis             = 'T'
+
+  stypvar(1)%cname          = 'NMass'
+  stypvar(1)%cunits         = 'Kg'
+  stypvar(1)%clong_name     = 'Icb_Mass_in_Northern_Hemisphere'
+  stypvar(1)%cshort_name    = 'NMass'
+
+  stypvar(2)%cname          = 'NMelt'
+  stypvar(2)%cunits         = 'Kg/s'
+  stypvar(2)%clong_name     = 'Icb_melt_in_Northern_Hemisphere'
+  stypvar(2)%cshort_name    = 'NMelt'
+
+  stypvar(3)%cname          = 'SVMass'
+  stypvar(3)%cunits         = 'Kg'
+  stypvar(3)%clong_name     = 'Icb_Mass_in_Southern_Hemisphere'
+  stypvar(3)%cshort_name    = 'SMass'
+
+  stypvar(4)%cname          = 'SMelt'
+  stypvar(4)%cunits         = 'Kg/s'
+  stypvar(4)%clong_name     = 'Icb_Melt_in_Southern_Hemisphere'
+  stypvar(4)%cshort_name    = 'SMelt'
+
+
+  e1(:,:) = getvar(cn_fhgr, cn_ve1t,  1, npiglo, npjglo)
+  e2(:,:) = getvar(cn_fhgr, cn_ve2t,  1, npiglo, npjglo)
+  ff(:,:) = getvar(cn_fhgr, cn_gphit, 1, npiglo, npjglo) ! only the sign of ff is important
+
+  ! modify the mask for periodic and north fold condition (T pivot, F Pivot ...)
+  ! in fact should be nice to use jperio as in the code ...
+  tmask(:,:)=getvar(cn_fmsk,'tmask',1,npiglo,npjglo)
+  SELECT CASE (nperio)
+  CASE (0) ! closed boundaries
+     ! nothing to do
+  CASE (4) ! ORCA025 type boundary
+     tmask(1:2,:)=0.
+     tmask(:,npjglo)=0.
+     tmask(npiglo/2+1:npiglo,npjglo-1)= 0.
+  CASE (6)
+     tmask(1:2,:)=0.
+     tmask(:,npjglo)=0.
+  CASE DEFAULT
+     PRINT *,' Nperio=', nperio,' not yet coded'
+     STOP
+  END SELECT
+
+  ricbmass(:,:)=0.
+  ricbmelt(:,:)=0.
+
+
+  IF (chkvar(cf_ifil, cn_iicbmass)) STOP
+
+  IF (chkvar(cf_ifil, cn_iicbmelt)) STOP
+  !
+  DO jt = 1, npt
+     IF (TRIM(cn_iicbmass) /= 'missing') ricbmass(:,:) = getvar(cf_ifil, cn_iicbmass, 1, npiglo, npjglo, ktime=jt)
+                                         ricbmelt(:,:) = getvar(cf_ifil, cn_iicbmelt, 1, npiglo, npjglo, ktime=jt)
+
+     ! North : ff > 0 
+     dmassn    = SUM( ricbmass (:,:)* e1(:,:) * e2(:,:) * tmask (:,:), (ff > 0 ) )
+     dmeltn    = SUM( ricbmelt (:,:)* e1(:,:) * e2(:,:) * tmask (:,:), (ff > 0 ) )
+
+     ! South : ff < 0
+     dmasss    = SUM( ricbmass (:,:)* e1(:,:) * e2(:,:) * tmask (:,:), (ff < 0) )
+     dmelts    = SUM( ricbmelt (:,:)* e1(:,:) * e2(:,:) * tmask (:,:), (ff < 0 )) 
+
+     PRINT *,' TIME = ', jt,' ( ',tim(jt),' )'
+     PRINT *,' Northern Hemisphere ' 
+     PRINT *,'          NMass (Kg)      ', dmassn
+     PRINT *,'          NMelt (Kg/s)    ', dmeltn
+     PRINT *
+     PRINT *,' Southern Hemisphere ' 
+     PRINT *,'          Mass (Kg)      ', dmasss
+     PRINT *,'          Melt (Kg/s)    ', dmelts
+
+     IF ( jt == 1 ) THEN
+        ! create output fileset
+        ncout = create      (cf_out, 'none',  ikx,      iky, ikz,     cdep='depthw'                   )
+        ierr  = createvar   (ncout,  stypvar, nboutput, ipk, id_varout                                )
+        ierr  = putheadervar(ncout,  cf_ifil, ikx,      iky, ikz,     pnavlon=rdumlon, pnavlat=rdumlat)
+
+        tim   = getvar1d(cf_ifil, cn_vtimec, npt     )
+        ierr  = putvar1d(ncout,   tim,       npt, 'T')
+     ENDIF
+
+     ! netcdf output 
+     ierr = putvar0d(ncout,id_varout(1), REAL(dmassn), ktime=jt)
+     ierr = putvar0d(ncout,id_varout(2), REAL(dmeltn), ktime=jt)
+     ierr = putvar0d(ncout,id_varout(3), REAL(dmasss), ktime=jt)
+     ierr = putvar0d(ncout,id_varout(4), REAL(dmelts), ktime=jt)
+
+  END DO ! time loop
+  ierr = closeout(ncout)
+
+END PROGRAM cdficb_diags
diff --git a/cdficediags.f90 b/src/cdficediags.f90
similarity index 67%
rename from cdficediags.f90
rename to src/cdficediags.f90
index c2651c3..613beda 100644
--- a/cdficediags.f90
+++ b/src/cdficediags.f90
@@ -1,3 +1,45 @@
+MODULE icediag
+
+CONTAINS
+
+    SUBROUTINE icediags(e1, e2, tmask, ff, ricethick, riceldfra, dvoln, darean, dextendn, &
+                        dextendn2, dvols, dareas, dextends, dextends2)
+        REAL(KIND=4), DIMENSION(:,:), INTENT(IN) :: e1, e2               ! metrics
+        REAL(KIND=4), DIMENSION(:,:), INTENT(IN) :: tmask, ff            ! npiglo x npjglo
+        REAL(KIND=4), DIMENSION(:,:), INTENT(IN) :: ricethick, riceldfra ! thickness, leadfrac (concentration)
+        REAL(KIND=8), INTENT(OUT)        :: dvols, dareas        ! volume, area extend South hemisphere
+        REAL(KIND=8), INTENT(OUT)        :: dextends, dextends2  ! volume, area extend South hemisphere
+        REAL(KIND=8), INTENT(OUT)        :: dvoln, darean        ! volume, area extend North hemisphere
+        REAL(KIND=8), INTENT(OUT)        :: dextendn, dextendn2
+
+
+        ! North : ff > 0
+        dvoln     = SUM( ricethick (:,:)* e1(:,:) * e2(:,:) * riceldfra (:,:) * tmask (:,:), (ff > 0 ) )
+        darean    = SUM(                  e1(:,:) * e2(:,:) * riceldfra (:,:) * tmask (:,:), (ff > 0 ) )
+        dextendn  = SUM(                  e1(:,:) * e2(:,:) * riceldfra (:,:) * tmask (:,:), (riceldfra > 0.15 .AND. ff > 0 ) )
+        ! JMM added 22/01/2007 : to compute same extent than the NSIDC
+        dextendn2 = SUM(                  e1(:,:) * e2(:,:)                   * tmask (:,:), (riceldfra > 0.15 .AND. ff > 0 ) )
+
+        ! South : ff < 0
+        dvols     = SUM( ricethick (:,:)* e1(:,:) * e2(:,:) * riceldfra (:,:) * tmask (:,:), (ff < 0 ) )
+        dareas    = SUM(                  e1(:,:) * e2(:,:) * riceldfra (:,:) * tmask (:,:), (ff < 0 ) )
+        dextends  = SUM(                  e1(:,:) * e2(:,:) * riceldfra (:,:) * tmask (:,:), (riceldfra > 0.15 .AND. ff < 0  ) )
+        dextends2 = SUM(                  e1(:,:) * e2(:,:)                   * tmask (:,:), (riceldfra > 0.15 .AND. ff < 0  ) )
+
+        dvoln = dvoln / 1d9
+        darean = darean / 1d9
+        dextendn = dextendn / 1d9
+        dextendn2 = dextendn2 / 1d9
+
+        dvols = dvols / 1d9
+        dareas = dareas / 1d9
+        dextends = dextends / 1d9
+        dextends2 = dextends2 / 1d9
+    END SUBROUTINE icediags
+
+END MODULE icediag
+
+
 PROGRAM cdficediag
   !!======================================================================
   !!                     ***  PROGRAM  cdficediag  ***
@@ -15,6 +57,7 @@ PROGRAM cdficediag
   !!----------------------------------------------------------------------
   USE cdfio
   USE modcdfnames
+  USE icediag
   !!----------------------------------------------------------------------
   !! CDFTOOLS_3.0 , MEOM 2011
   !! $Id$
@@ -23,13 +66,13 @@ PROGRAM cdficediag
   !!----------------------------------------------------------------------
   IMPLICIT NONE
 
-  INTEGER(KIND=4)                            :: jk, jj, jt           ! dummy loop index
+  INTEGER(KIND=4)                            :: jt           ! dummy loop index
   INTEGER(KIND=4)                            :: ierr                 ! working integer
-  INTEGER(KIND=4)                            :: narg, iargc          ! command line 
+  INTEGER(KIND=4)                            :: narg, iargc          ! command line
+  INTEGER(KIND=4)                            :: ijarg, ireq         ! command line
   INTEGER(KIND=4)                            :: npiglo, npjglo, npt  ! size of the domain
-  INTEGER(KIND=4)                            :: nvpk                 ! vertical levels in working variable
   INTEGER(KIND=4)                            :: nperio = 4           ! boundary condition ( periodic, north fold)
-  INTEGER(KIND=4)                            :: ikx=1, iky=1, ikz=1  ! dims of netcdf output file
+  INTEGER(KIND=4)                            :: ikx=1, iky=1, ikz=0  ! dims of netcdf output file
   INTEGER(KIND=4)                            :: nboutput=8           ! number of values to write in cdf output
   INTEGER(KIND=4)                            :: ncout                ! for netcdf output
   INTEGER(KIND=4), DIMENSION(:), ALLOCATABLE :: ipk, id_varout
@@ -50,6 +93,7 @@ PROGRAM cdficediag
   CHARACTER(LEN=256)                         :: cf_ifil              ! input ice file
   CHARACTER(LEN=256)                         :: cf_out='icediags.nc' ! output file
   CHARACTER(LEN=256)                         :: cldum                ! dummy string
+  CHARACTER(LEN=256)                         :: cn_mask='tmask'      ! mask variable name
   !
   LOGICAL                                    :: lchk  = .false.      ! missing file flag
   LOGICAL                                    :: llim3 = .false.      ! LIM3 flag
@@ -75,6 +119,7 @@ PROGRAM cdficediag
      PRINT *,'      '
      PRINT *,'     OPTION :'
      PRINT *,'       [-lim3 ] : LIM3 variable name convention is used'
+     PRINT *,'       [-o OUT-file ] : specify output file instead of ',TRIM(cf_out)
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'        ',TRIM(cn_fhgr),' and ',TRIM(cn_fmsk)
@@ -92,23 +137,35 @@ PROGRAM cdficediag
   ENDIF
 
   CALL getarg (1, cf_ifil)
-
-  lchk = lchk .OR. chkfile(cn_fhgr) 
-  lchk = lchk .OR. chkfile(cn_fmsk) 
+  
+  ijarg = 1 ; ireq = 0
+  
+  DO WHILE ( ijarg <= narg )
+    CALL getarg (ijarg, cldum   ) ; ijarg = ijarg + 1 
+    SELECT CASE ( cldum )
+    CASE ( '-lim3'    ) ; llim3 = .true.
+    CASE ( '-lim2' ) ; llim3 = .false.
+    CASE ( '-mask' ) ;
+        CALL getarg (ijarg, cn_mask) ; ijarg=ijarg+1
+    CASE ( '-maskfile' ) ;
+        CALL getarg (ijarg, cn_fmsk) ; ijarg=ijarg+1
+    CASE ('-o') 
+        CALL getarg (ijarg, cf_out) ; ijarg=ijarg+1
+    CASE DEFAULT 
+      ireq=ireq+1
+      SELECT CASE ( ireq )
+      CASE ( 1 )    ; cf_ifil=cldum
+      CASE DEFAULT  ; PRINT *,' Too many arguments'
+      END SELECT
+    END SELECT
+  END DO
+
+  lchk = lchk .OR. chkfile(cn_fhgr)
+  lchk = lchk .OR. chkfile(cn_fmsk)
   lchk = lchk .OR. chkfile(cf_ifil)
 
   IF ( lchk ) STOP ! missing file
 
-  IF ( narg == 2 ) THEN
-     CALL getarg (2, cldum)
-     IF (TRIM(cldum) == '-lim3') THEN
-        llim3 = .true.
-     ELSE IF (TRIM(cldum) == '-lim2') THEN
-     ELSE
-        PRINT *,' For this sea-ice data format use a namelist '
-     END IF
-  END IF
-
   npiglo = getdim (cf_ifil,cn_x)
   npjglo = getdim (cf_ifil,cn_y)
   npt    = getdim (cf_ifil,cn_t)
@@ -180,7 +237,7 @@ PROGRAM cdficediag
 
   ! modify the mask for periodic and north fold condition (T pivot, F Pivot ...)
   ! in fact should be nice to use jperio as in the code ...
-  tmask(:,:)=getvar(cn_fmsk,'tmask',1,npiglo,npjglo)
+  tmask(:,:)=getvar(cn_fmsk,cn_mask,1,npiglo,npjglo)
   SELECT CASE (nperio)
   CASE (0) ! closed boundaries
      ! nothing to do
@@ -218,31 +275,20 @@ PROGRAM cdficediag
      IF (TRIM(cn_iicethic) .NE. 'missing') ricethick(:,:) = getvar(cf_ifil, cn_iicethic, 1, npiglo, npjglo, ktime=jt)
      riceldfra(:,:) = getvar(cf_ifil, cn_ileadfra, 1, npiglo, npjglo, ktime=jt)
 
-     ! North : ff > 0 
-     dvoln     = SUM( ricethick (:,:)* e1(:,:) * e2(:,:) * riceldfra (:,:) * tmask (:,:), (ff > 0 ) )
-     darean    = SUM(                  e1(:,:) * e2(:,:) * riceldfra (:,:) * tmask (:,:), (ff > 0 ) )
-     dextendn  = SUM(                  e1(:,:) * e2(:,:) * riceldfra (:,:) * tmask (:,:), (riceldfra > 0.15 .AND. ff > 0 ) )
-     ! JMM added 22/01/2007 : to compute same extent than the NSIDC
-     dextendn2 = SUM(                  e1(:,:) * e2(:,:)                   * tmask (:,:), (riceldfra > 0.15 .AND. ff > 0 ) )
-
-     ! South : ff < 0
-     dvols     = SUM( ricethick (:,:)* e1(:,:) * e2(:,:) * riceldfra (:,:) * tmask (:,:), (ff < 0 ) )
-     dareas    = SUM(                  e1(:,:) * e2(:,:) * riceldfra (:,:) * tmask (:,:), (ff < 0 ) )
-     dextends  = SUM(                  e1(:,:) * e2(:,:) * riceldfra (:,:) * tmask (:,:), (riceldfra > 0.15 .AND. ff < 0  ) )
-     dextends2 = SUM(                  e1(:,:) * e2(:,:)                   * tmask (:,:), (riceldfra > 0.15 .AND. ff < 0  ) )
+     CALL icediags(e1, e2, tmask, ff, ricethick, riceldfra, dvoln, darean, dextendn, dextendn2, dvols, dareas, dextends, dextends2)
 
      PRINT *,' TIME = ', jt,' ( ',tim(jt),' )'
      PRINT *,' Northern Hemisphere ' 
-     PRINT *,'          NVolume (10^9 m3)  ', dvoln     /1.d9
-     PRINT *,'          NArea (10^9 m2)    ', darean    /1.d9
-     PRINT *,'          NExtend (10^9 m2)  ', dextendn  /1.d9
-     PRINT *,'          NExnsidc (10^9 m2) ', dextendn2 /1.d9
+     PRINT *,'          NVolume (10^9 m3)  ', dvoln
+     PRINT *,'          NArea (10^9 m2)    ', darean
+     PRINT *,'          NExtend (10^9 m2)  ', dextendn
+     PRINT *,'          NExnsidc (10^9 m2) ', dextendn2
      PRINT *
      PRINT *,' Southern Hemisphere ' 
-     PRINT *,'          SVolume (10^9 m3)  ', dvols     /1.d9
-     PRINT *,'          SArea (10^9 m2)    ', dareas    /1.d9
-     PRINT *,'          SExtend (10^9 m2)  ', dextends  /1.d9
-     PRINT *,'          SExnsidc (10^9 m2) ', dextends2 /1.d9
+     PRINT *,'          SVolume (10^9 m3)  ', dvols
+     PRINT *,'          SArea (10^9 m2)    ', dareas
+     PRINT *,'          SExtend (10^9 m2)  ', dextends
+     PRINT *,'          SExnsidc (10^9 m2) ', dextends2
 
      IF ( jt == 1 ) THEN
         ! create output fileset
@@ -255,16 +301,17 @@ PROGRAM cdficediag
      ENDIF
 
      ! netcdf output 
-     ierr = putvar0d(ncout,id_varout(1), REAL(dvoln     /1.d9), ktime=jt)
-     ierr = putvar0d(ncout,id_varout(2), REAL(darean    /1.d9), ktime=jt)
-     ierr = putvar0d(ncout,id_varout(3), REAL(dextendn  /1.d9), ktime=jt)
-     ierr = putvar0d(ncout,id_varout(4), REAL(dextendn2 /1.d9), ktime=jt)
-     ierr = putvar0d(ncout,id_varout(5), REAL(dvols     /1.d9), ktime=jt)
-     ierr = putvar0d(ncout,id_varout(6), REAL(dareas    /1.d9), ktime=jt)
-     ierr = putvar0d(ncout,id_varout(7), REAL(dextends  /1.d9), ktime=jt)
-     ierr = putvar0d(ncout,id_varout(8), REAL(dextends2 /1.d9), ktime=jt)
-
+     ierr = putvar0d(ncout,id_varout(1), REAL(dvoln     ), ktime=jt)
+     ierr = putvar0d(ncout,id_varout(2), REAL(darean    ), ktime=jt)
+     ierr = putvar0d(ncout,id_varout(3), REAL(dextendn  ), ktime=jt)
+     ierr = putvar0d(ncout,id_varout(4), REAL(dextendn2 ), ktime=jt)
+     ierr = putvar0d(ncout,id_varout(5), REAL(dvols     ), ktime=jt)
+     ierr = putvar0d(ncout,id_varout(6), REAL(dareas    ), ktime=jt)
+     ierr = putvar0d(ncout,id_varout(7), REAL(dextends  ), ktime=jt)
+     ierr = putvar0d(ncout,id_varout(8), REAL(dextends2 ), ktime=jt)
   END DO ! time loop
   ierr = closeout(ncout)
 
 END PROGRAM cdficediag
+
+
diff --git a/cdfimprovechk.f90 b/src/cdfimprovechk.f90
similarity index 100%
rename from cdfimprovechk.f90
rename to src/cdfimprovechk.f90
diff --git a/cdfinfo.f90 b/src/cdfinfo.f90
similarity index 71%
rename from cdfinfo.f90
rename to src/cdfinfo.f90
index b6e8d05..85dbb67 100644
--- a/cdfinfo.f90
+++ b/src/cdfinfo.f90
@@ -19,24 +19,31 @@ PROGRAM cdfinfo
   !!----------------------------------------------------------------------
   IMPLICIT NONE
 
-  INTEGER(KIND=4)                               :: jvar                     ! dummy loop index
+  INTEGER(KIND=4)                               :: jvar, jarg               ! dummy loop index
   INTEGER(KIND=4)                               :: ierr                     ! working integer
-  INTEGER(KIND=4)                               :: narg, iargc              ! 
+  INTEGER(KIND=4)                               :: narg, iargc, ijarg       ! 
   INTEGER(KIND=4)                               :: npiglo, npjglo, npk ,npt ! size of the domain
   INTEGER(KIND=4)                               :: nvars                    ! Number of variables in a file
+  INTEGER(KIND=4), DIMENSION(1)                 :: ikloc                    ! used for MINLOC
+
+  REAL(KIND=4)                                  :: zdep                     ! depth to look for
+  REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: zdept                    ! depth array
 
   CHARACTER(LEN=256)                            :: cf_in                    ! file name
   CHARACTER(LEN=256)                            :: cv_dep                   ! depth name
+  CHARACTER(LEN=256)                            :: cl_dum                   ! dummy input variable
   CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_names                 ! array of var name
   
   TYPE(variable), DIMENSION(:),     ALLOCATABLE :: stypvar                  ! variable attributes
+  
+  LOGICAL                                       :: ldep                     ! flag for depth control
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
   narg= iargc()
 
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfinfo ''model cdf file'' '
+     PRINT *,' usage : cdfinfo ''model cdf file'' [-dep dep] '
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
      PRINT *,'        Gives very basic information about the file given in arguments.'
@@ -44,6 +51,9 @@ PROGRAM cdfinfo
      PRINT *,'     ARGUMENTS :'
      PRINT *,'        model output file in netcdf.' 
      PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'        [-dep depth ] : return the nearest k index corresponding to depth '
+     PRINT *,'      '
      PRINT *,'     OUTPUT : '
      PRINT *,'        On standard ouput, gives the size of the domain, the depth '
      PRINT *,'        dimension name, the number of variables.'
@@ -52,6 +62,15 @@ PROGRAM cdfinfo
   ENDIF
 
   CALL getarg (1, cf_in)
+  ijarg = 2
+  DO WHILE ( ijarg <= narg )
+     CALL getarg (ijarg, cl_dum) ; ijarg = ijarg+1
+     SELECT CASE ( cl_dum)
+     CASE ('-dep' ) ; CALL getarg( ijarg, cl_dum); ijarg = ijarg+1; ; READ(cl_dum,*) zdep ; ldep =.true.
+     CASE DEFAULT   ; PRINT *, 'Option ',TRIM(cl_dum),' ignored ...'
+     END SELECT
+  ENDDO
+        
   IF ( chkfile(cf_in) ) STOP ! missing file
 
   npiglo = getdim (cf_in,cn_x)
@@ -94,7 +113,14 @@ PROGRAM cdfinfo
   cv_names(:)=getvarname(cf_in, nvars, stypvar)
 
   DO jvar = 1, nvars
-   PRINT *, 'variable# ',jvar,' is : ',TRIM(cv_names(jvar))
+     PRINT *, 'variable# ',jvar,' is : ',TRIM(cv_names(jvar))
   END DO
 
+  IF ( ldep ) THEN
+      ALLOCATE(zdept(npk) )
+      zdept = getdimvar (cf_in,  npk)
+      ikloc= MINLOC( ABS(zdept - zdep) )
+      PRINT * ,' NEAREST_K ',ikloc(1)
+  ENDIF
+
 END PROGRAM cdfinfo
diff --git a/cdfio.f90 b/src/cdfio.F90
similarity index 72%
rename from cdfio.f90
rename to src/cdfio.F90
index a9b52ea..a1bcb81 100644
--- a/cdfio.f90
+++ b/src/cdfio.F90
@@ -33,6 +33,7 @@
   !!   getnvar       : get the number of variable in a file
   !!   getspval      : get spval of a given variable
   !!   getvar1d      : read 1D variable (eg depth, time_counter) from a file
+  !!   getvar3d      : read 3D variable  at once
   !!   getvaratt     : read variable attributes
   !!   gettimeatt    : get time attributes
   !!   getvar        : read the variable
@@ -42,6 +43,7 @@
   !!   getvarxz      : get a x-z slice of 3D data
   !!   getvaryz      : get a y-z slice of 3D data
   !!   getvdim       : get the number of dim of a variable
+  !!   getvardim     : get the values of the vertical coordinates variable
   !!   ncopen        : open a netcdf file and return its ncid
   !!   putatt        : write variable attribute
   !!   puttimeatt    : write time variable attribute
@@ -88,6 +90,7 @@
      REAL(KIND=4)       :: add_offset=0.     !# add offset
      REAL(KIND=4)       :: savelog10=0.      !# flag for log10 transform
      INTEGER(KIND=4)    :: iwght=1           !# weight of the variable for cdfmoy_weighted
+     INTEGER(KIND=4), DIMENSION(4) :: ichunk !# chunksize
      CHARACTER(LEN=256) :: clong_name        !# Long Name of the variable
      CHARACTER(LEN=256) :: cshort_name       !# short name of the variable
      CHARACTER(LEN=256) :: conline_operation !# ???
@@ -95,6 +98,48 @@
      CHARACTER(LEN=256) :: cprecision='r4'   !# possible values are i2, r4, r8
   END TYPE variable
 
+  TYPE, PUBLIC  :: ncfile                         ! logical structure reflecting file structure
+     INTEGER(KIND=4)                              :: ncid    ! file ncid
+     INTEGER(KIND=4)                              :: ndims   ! number of dims
+     INTEGER(KIND=4)                              :: nvars   ! number of vars
+     INTEGER(KIND=4)                              :: natts   ! number of global attributes
+     INTEGER(KIND=4)                              :: iunlim  ! ID of unlimited dimension
+     INTEGER(KIND=4)                              :: npi     ! i-size of file
+     INTEGER(KIND=4)                              :: npj     ! j-size of file
+     INTEGER(KIND=4)                              :: npk     ! k-size of file
+     INTEGER(KIND=4)                              :: npt     ! t-size of file
+     INTEGER(KIND=4)                              :: npb     ! time_bound size
+     INTEGER(KIND=4)                              :: idx     ! x dimid
+     INTEGER(KIND=4)                              :: idy     ! y dimid
+     INTEGER(KIND=4)                              :: idz     ! z dimid
+     INTEGER(KIND=4)                              :: idt     ! t dimid
+     INTEGER(KIND=4)                              :: idb     ! time-bound  dimid
+     INTEGER(KIND=4), DIMENSION(:),   ALLOCATABLE :: ideflat ! deflate level (nvar)
+     INTEGER(KIND=4), DIMENSION(:),   ALLOCATABLE :: nvatt   ! number of att of each variable (var)
+     INTEGER(KIND=4), DIMENSION(:),   ALLOCATABLE :: nvid    ! varid of each variable (var)
+     INTEGER(KIND=4), DIMENSION(:),   ALLOCATABLE :: nvdim   ! dimension of each variable (var)
+     INTEGER(KIND=4), DIMENSION(:),   ALLOCATABLE :: itype   ! type of each variable (var)
+     INTEGER(KIND=4), DIMENSION(:),   ALLOCATABLE :: nlen    ! len of each dimension ( ndims)
+     INTEGER(KIND=4), DIMENSION(:,:), ALLOCATABLE :: ichunk  ! size of chunk (nvar, ndims)
+     INTEGER(KIND=4), DIMENSION(:,:), ALLOCATABLE :: idimids ! dimids of each variable (nvar, ndims) 
+     CHARACTER(LEN=255)                            :: c_fnam ! name of working file
+     CHARACTER(LEN=80 ), DIMENSION(:), ALLOCATABLE :: c_vnam ! name of each variable (var)
+     CHARACTER(LEN=80 ), DIMENSION(:), ALLOCATABLE :: c_dnam ! name of each dimension (ndims)
+     LOGICAL,           DIMENSION(:), ALLOCATABLE :: lconti  ! contiguous flag (nvar)
+     !   extra information for global attribute 
+     INTEGER(KIND=4)                :: number_total          ! DOMAIN_number_total
+     INTEGER(KIND=4)                :: number                ! DOMAIN_number
+     INTEGER(KIND=4), DIMENSION(2)  :: idimensions_ids       ! DOMAIN_dimensions_ids
+     INTEGER(KIND=4), DIMENSION(2)  :: isize_global          ! DOMAIN_size_global
+     INTEGER(KIND=4), DIMENSION(2)  :: isize_local           ! DOMAIN_size_local
+     INTEGER(KIND=4), DIMENSION(2)  :: iposition_first       ! DOMAIN_position_first
+     INTEGER(KIND=4), DIMENSION(2)  :: iposition_last        ! DOMAIN_position_last 
+     INTEGER(KIND=4), DIMENSION(2)  :: ihalo_size_start      ! DOMAIN_halo_size_start
+     INTEGER(KIND=4), DIMENSION(2)  :: ihalo_size_end        ! DOMAIN_halo_size_end
+     CHARACTER(LEN=80)              :: c_type                ! DOMAIN_type
+  END TYPE ncfile
+
+
   INTEGER(KIND=4), PARAMETER :: jp_missing_nm = 3
   
   CHARACTER(LEN=256), DIMENSION(jp_missing_nm) :: & ! take care of same length for each element
@@ -102,7 +147,7 @@
   CHARACTER(LEN=256 ) :: cl_dum              !# dummy char argument
 
   INTERFACE putvar
-     MODULE PROCEDURE putvarr8, putvarr4, putvari2, putvarzo, reputvarr4
+     MODULE PROCEDURE putvarr8, putvarr4, putvari2, putvarzo, reputvarr4, putvare3
   END INTERFACE
 
   INTERFACE putvar1d   
@@ -120,8 +165,8 @@
   PUBLIC :: chkfile, chkvar
   PUBLIC :: copyatt, create, createvar, getvaratt, cvaratt, gettimeatt
   PUBLIC :: putatt, putheadervar, putvar, putvar1d, putvar0d, atted, puttimeatt
-  PUBLIC :: getatt, getdim, getvdim, getipk, getnvar, getvarname, getvarid, getspval
-  PUBLIC :: getvar, getvarxz, getvaryz, getvar1d, getvare3
+  PUBLIC :: getatt, getdim, getvdim, getdimvar,getipk, getnvar, getvarname, getvarid
+  PUBLIC :: getvar, getvarxz, getvaryz, getvar1d, getvare3, getvar3d, getvar3dt, getvar4d, getspval
   PUBLIC :: gettimeseries
   PUBLIC :: closeout, ncopen
   PUBLIC :: ERR_HDL
@@ -202,7 +247,7 @@ CONTAINS
 
 
   INTEGER(KIND=4) FUNCTION create( cdfile, cdfilref ,kx,ky,kz ,cdep, cdepvar, &
-       &                           cdlonvar, cdlatvar,  ld_xycoo)
+       &                           cdlonvar, cdlatvar,  ld_xycoo, ld_nc4 )
     !!---------------------------------------------------------------------
     !!                  ***  FUNCTION create  ***
     !!
@@ -220,13 +265,27 @@ CONTAINS
     CHARACTER(LEN=*), OPTIONAL, INTENT(in) :: cdlonvar ! name of 1D longitude
     CHARACTER(LEN=*), OPTIONAL, INTENT(in) :: cdlatvar ! name of 1D latitude
     LOGICAL,          OPTIONAL, INTENT(in) :: ld_xycoo ! if false then DO NOT read nav_lat nav_lat from input file
+    LOGICAL,          OPTIONAL, INTENT(in) :: ld_nc4   ! create NETCDF4 file with chunking and deflation
 
     INTEGER(KIND=4)               :: istatus, icout, incid, idum
     INTEGER(KIND=4) ,DIMENSION(4) :: invdim
     CHARACTER(LEN=256)            :: cldep, cldepref, cldepvar, clonvar, clatvar
-    LOGICAL                       :: ll_xycoo
+    LOGICAL                       :: ll_xycoo, ll_nc4
     !!----------------------------------------------------------------------
+    IF ( PRESENT (ld_nc4 ) ) THEN 
+       ll_nc4 = ld_nc4
+    ELSE
+       ll_nc4 = .false. 
+    ENDIF
+#if defined key_netcdf4
+    IF ( ll_nc4 ) THEN
+      istatus = NF90_CREATE(cdfile,cmode=or(NF90_CLOBBER,NF90_NETCDF4     ), ncid=icout)
+    ELSE
+      istatus = NF90_CREATE(cdfile,cmode=or(NF90_CLOBBER,NF90_64BIT_OFFSET), ncid=icout)
+    ENDIF
+#else
     istatus = NF90_CREATE(cdfile,cmode=or(NF90_CLOBBER,NF90_64BIT_OFFSET), ncid=icout)
+#endif
     istatus = NF90_DEF_DIM(icout, cn_x, kx, nid_x)
     istatus = NF90_DEF_DIM(icout, cn_y, ky, nid_y)
 
@@ -298,7 +357,7 @@ CONTAINS
   END FUNCTION create
 
 
-  INTEGER(KIND=4) FUNCTION createvar(kout, sdtyvar, kvar, kpk, kidvo, cdglobal)
+  INTEGER(KIND=4) FUNCTION createvar(kout, sdtyvar, kvar, kpk, kidvo, cdglobal, ld_nc4)
     !!---------------------------------------------------------------------
     !!                  ***  FUNCTION createvar  ***
     !!
@@ -318,12 +377,20 @@ CONTAINS
     INTEGER(KIND=4), DIMENSION(kvar), INTENT(in) :: kpk     ! number of level/var
     INTEGER(KIND=4), DIMENSION(kvar), INTENT(out):: kidvo   ! varid's of output var
     CHARACTER(LEN=*), OPTIONAL,       INTENT(in) :: cdglobal! Global Attribute
+    LOGICAL         , OPTIONAL,       INTENT(in) :: ld_nc4  ! user chunking and deflation
 
     INTEGER(KIND=4)               :: jv             ! dummy loop index
     INTEGER(KIND=4)               :: idims, istatus 
-    INTEGER(KIND=4), DIMENSION(4) :: iidims
+    INTEGER(KIND=4), DIMENSION(4) :: iidims, ichunk
     INTEGER(KIND=4)               :: iprecision
+    LOGICAL                       :: ll_nc4
     !!----------------------------------------------------------------------
+    IF ( PRESENT (ld_nc4 ) ) THEN 
+       ll_nc4 = ld_nc4
+    ELSE
+       ll_nc4 = .false. 
+    ENDIF
+
     DO jv = 1, kvar
        ! Create variables whose name is not 'none'
        IF ( sdtyvar(jv)%cname /= 'none' ) THEN
@@ -333,6 +400,9 @@ CONTAINS
           ELSE IF (kpk(jv) > 1 ) THEN
              idims=4
              iidims(1) = nid_x ; iidims(2) = nid_y ; iidims(3) = nid_z ; iidims(4) = nid_t
+          ELSE IF (kpk(jv) < 0 ) THEN
+             idims=1
+             iidims(1) = nid_t 
           ELSE
              PRINT *,' ERROR: ipk = ',kpk(jv), jv , sdtyvar(jv)%cname
              STOP
@@ -353,8 +423,16 @@ CONTAINS
              ENDIF
           END SELECT
 
+#if defined key_netcdf4
+         IF ( ll_nc4 ) THEN
+          istatus = NF90_DEF_VAR(kout, sdtyvar(jv)%cname, iprecision, iidims(1:idims) ,kidvo(jv), & 
+                  &               chunksizes=sdtyvar(jv)%ichunk(1:idims), deflate_level=1 )
+         ELSE
           istatus = NF90_DEF_VAR(kout, sdtyvar(jv)%cname, iprecision, iidims(1:idims) ,kidvo(jv) )
-
+         ENDIF
+#else
+          istatus = NF90_DEF_VAR(kout, sdtyvar(jv)%cname, iprecision, iidims(1:idims) ,kidvo(jv) )
+#endif
           ! add attributes
           istatus = putatt(sdtyvar(jv), kout, kidvo(jv), cdglobal=cdglobal)
           createvar=istatus
@@ -467,7 +545,7 @@ CONTAINS
     !!----------------------------------------------------------------------
     INTEGER(KIND=4),     INTENT(in) :: kout
     CHARACTER(LEN=20),  INTENT(in)  :: cdvartime
-    CHARACTER(LEN=256), INTENT(out) :: ctcalendar, cttitle, ctlong_name, ctaxis, ctunits, cttime_origin
+    CHARACTER(LEN=256), INTENT(in) :: ctcalendar, cttitle, ctlong_name, ctaxis, ctunits, cttime_origin
 
     INTEGER(KIND=4) :: ivarid
     !!----------------------------------------------------------------------
@@ -516,11 +594,12 @@ CONTAINS
     istatus = NF90_REDEF(incid)
     istatus = NF90_INQ_VARID(incid, cdvar, ivarid)
 
-    istatus=NF90_RENAME_ATT(incid, ivarid, 'units',         cdunits        )
-    zspval = getspval      ( cdfile, cdvar, clmissing                       )
-    istatus=NF90_PUT_ATT   (incid, ivarid, clmissing, pmissing_value        )
-    istatus=NF90_RENAME_ATT(incid, ivarid, 'long_name',     cdlong_name    )
-    istatus=NF90_RENAME_ATT(incid, ivarid, 'short_name',    cdshort_name   )
+!   istatus=NF90_RENAME_ATT(incid, ivarid, 'units',         cdunits        )
+    istatus=NF90_PUT_ATT(incid, ivarid, 'units',         cdunits        )
+    zspval = getspval   ( cdfile, cdvar, clmissing                       )
+    istatus=NF90_PUT_ATT(incid, ivarid, clmissing, pmissing_value        )
+    istatus=NF90_PUT_ATT(incid, ivarid, 'long_name',     cdlong_name    )
+    istatus=NF90_PUT_ATT(incid, ivarid, 'short_name',    cdshort_name   )
 
     istatus=NF90_ENDDEF(incid)
     cvaratt=istatus
@@ -735,8 +814,10 @@ CONTAINS
     !!-----------------------------------------------------------
     clnam = '-------------'
 
-    IF ( PRESENT(kstatus) ) kstatus=0
-    IF ( PRESENT(ldexact) ) lexact=ldexact
+    IF ( PRESENT(kstatus)  ) kstatus=0
+    IF ( PRESENT(ldexact)  ) lexact=ldexact
+    IF ( cdim_name == cn_x ) lexact=.true.  ! fix for XIOS files having now a new dimension xaxis_bound which match getdim ('x') ....
+                                            ! more clever fix must be found for identification of the dimensions in the input files
     istatus=NF90_OPEN(cdfile, NF90_NOWRITE, incid)
     IF ( istatus == NF90_NOERR ) THEN
        istatus=NF90_INQUIRE(incid, ndimensions=idims)
@@ -912,6 +993,49 @@ CONTAINS
 
   END FUNCTION getvdim
 
+  FUNCTION getdimvar (cdfile, kpk, cd_depnam)
+    !!---------------------------------------------------------------------
+    !!                  ***  FUNCTION getdimvar  ***
+    !!
+    !! ** Purpose :  Try to infer the name of the depth variable associated
+    !!               with z dimension, and return the values as a 1d array 
+    !!
+    !! ** Method  :  Trial and error method ... 
+    !!
+    !!----------------------------------------------------------------------
+    CHARACTER(LEN=*), INTENT(in) :: cdfile
+    INTEGER(KIND=4),  INTENT(in) :: kpk
+    REAL(KIND=4), DIMENSION(kpk) :: getdimvar
+    CHARACTER(LEN=*), OPTIONAL, INTENT(out) :: cd_depnam
+
+    INTEGER(KIND=4) :: ji
+    INTEGER(KIND=4) :: incid, idims, iuldid, idimv, ivars, istatus
+    INTEGER(KIND=4), DIMENSION(4) :: idimt
+    CHARACTER(LEN=80) :: clvar ='none'
+    
+    !!----------------------------------------------------------------------
+    istatus = NF90_OPEN   (cdfile,NF90_NOWRITE,incid)
+    istatus = NF90_INQUIRE(incid, ndimensions=idims, unlimiteddimid=iuldid,&
+                  &              nvariables=ivars)
+    ! look for variables with only one dim, not unlimited dim ...
+    DO ji = 1, ivars
+       istatus = NF90_INQUIRE_VARIABLE(incid, ji, name=clvar, ndims=idimv, &
+                  & dimids=idimt )
+       IF ( idimv == 1 ) THEN ! candidate
+          IF ( idimt(1) /= iuldid) THEN ! this is The Variable
+             PRINT *, ' Found vertical variable :', TRIM(clvar)
+             istatus = NF90_GET_VAR(incid, ji, getdimvar(:) )
+             EXIT
+          ENDIF
+       ENDIF
+    ENDDO
+    IF ( present(cd_depnam) ) cd_depnam=TRIM(clvar)
+    IF ( ji == ivars +1 ) THEN
+       PRINT *,'Sorry, no vertical dim variables inferred ...'
+       getdimvar=0.
+    ENDIF
+
+  END FUNCTION
 
   INTEGER(KIND=4) FUNCTION  getnvar (cdfile)
     !!---------------------------------------------------------------------
@@ -1006,6 +1130,7 @@ CONTAINS
        istatus=NF90_INQUIRE_VARIABLE(incid, jv, name=getvarname(jv) )
        sdtypvar(jv)%cname=getvarname(jv)
 
+
        ! look for standard attibutes
        IF ( NF90_INQUIRE_ATTRIBUTE(incid, jv, 'units', len=ilen) == NF90_NOERR ) THEN
           istatus=NF90_GET_ATT(incid, jv, 'units', cldum(1:ilen))
@@ -1100,7 +1225,7 @@ CONTAINS
     REAL(KIND=4), DIMENSION(kpi,kpj) :: getvar            ! 2D REAL 4 holding variable field at klev
 
     INTEGER(KIND=4), DIMENSION(4)               :: istart, icount, inldim
-    INTEGER(KIND=4)                             :: incid, id_var, id_dimunlim, inbdim
+    INTEGER(KIND=4)                             :: incid, id_var, id_dimunlim, inbdim, inbdim2
     INTEGER(KIND=4)                             :: istatus, ilev, imin, jmin
     INTEGER(KIND=4)                             :: itime, ilog, ipiglo, imax
     INTEGER(KIND=4), SAVE                       :: ii, ij, ik0, ji, jj, ik1, ik
@@ -1110,6 +1235,10 @@ CONTAINS
     CHARACTER(LEN=256)                          :: clvar
     LOGICAL                                     :: lliom=.false., llperio=.false.
     LOGICAL                                     :: llog=.FALSE. , lsf=.FALSE. , lao=.FALSE.
+    !!
+    INTEGER(KIND=4)                :: ityp
+    !INTEGER(KIND=4), DIMENSION(:)  :: dimids
+    !INTEGER(KIND=4)                :: nAtts
     !!---------------------------------------------------------------------
     llperio=.false.
     IF (PRESENT(klev) ) THEN
@@ -1159,10 +1288,14 @@ CONTAINS
 
     IF ( lliom) THEN  ! try to detect if input file is a zgr IOM file, looking for e3t_0
       istatus=NF90_INQ_VARID( incid,'e3t_0', id_var)
+      istatus=NF90_INQUIRE_VARIABLE( incid, id_var, xtype=ityp, ndims=inbdim) !, dimids, nAtts)
       IF ( istatus == NF90_NOERR ) THEN
         ! iom file , change names
         ! now try to detect if it is v2 or v3, in v3, e3t_ps exist and is a 2d variable
-         istatus=NF90_INQ_VARID( incid,'e3t_ps', id_var)
+         istatus=          NF90_INQ_VARID( incid,'e3t_ps', id_var)
+         istatus=istatus + NF90_INQUIRE_VARIABLE( incid, id_var, xtype=ityp, ndims=inbdim2) !, dimids, nAtts)
+         !istatus2=NF90_INQUIRE_VAR( incid, id_var, 'e3t_0', xtype, ndims, dimids, nAtts)
+         PRINT *, 'e3t_0 has' , inbdim, 'dimensions'
          IF ( istatus == NF90_NOERR ) THEN  
            ! case of NEMO_v3 zfr files
            ! look for mbathy and out it in memory, once for all
@@ -1214,10 +1347,20 @@ CONTAINS
            ENDIF
           ! zgr v3
           SELECT CASE ( clvar )
-           CASE ('e3u_ps')  ; clvar='e3t_ps'
-           CASE ('e3v_ps')  ; clvar='e3t_ps'
+           CASE ('e3u_ps')  ; clvar='e3u_ps'
+           CASE ('e3v_ps')  ; clvar='e3v_ps'
            CASE ('e3w_ps')  ; clvar='e3w_ps'
           END SELECT
+
+         ELSEIF ( inbdim>2 ) THEN
+          !  case of NEMO_V3.6 STABLE zgr file
+          SELECT CASE ( clvar )
+           CASE ('e3t_ps')  ; clvar='e3t_0'
+           CASE ('e3u_ps')  ; clvar='e3u_0'
+           CASE ('e3v_ps')  ; clvar='e3v_0'
+           CASE ('e3w_ps')  ; clvar='e3w_0'
+          END SELECT
+          
          ELSE
           ! zgr v2
           SELECT CASE ( clvar )
@@ -1426,10 +1569,331 @@ CONTAINS
 
   END FUNCTION getvar
 
+  FUNCTION  getvar3d (cdfile,cdvar,kpi,kpj,kpz, kimin, kjmin, kkmin, ktime )
+    !!---------------------------------------------------------------------
+    !!                  ***  FUNCTION  getvar3d  ***
+    !!
+    !! ** Purpose : Return the 3D REAL variable cdvar(x,y,z), from cdfile 
+    !!              kpi,kpj,kpz are the horizontal size of the 3D variable
+    !!              Sub domain can be optionaly specified with its starting
+    !!              point, kimin, kjmin, kkmin
+    !!
+    !! ** Method  : Use NF90 primitive to read the block of 3D data
+    !!
+    !!---------------------------------------------------------------------
+    CHARACTER(LEN=*),          INTENT(in) :: cdfile
+    CHARACTER(LEN=*),          INTENT(in) :: cdvar
+    INTEGER(KIND=4),           INTENT(in) :: kpi,   kpj,   kpz
+    INTEGER(KIND=4), OPTIONAL, INTENT(in) :: kimin, kjmin, kkmin
+    INTEGER(KIND=4), OPTIONAL, INTENT(in) :: ktime         ! Optional variable. If missing 1 is assumed 
+    REAL(KIND=4), DIMENSION(kpi,kpj,kpz)  :: getvar3d      ! 3D REAL 
+
+    INTEGER(KIND=4), DIMENSION(4) :: istart, icount
+    INTEGER(KIND=4)               :: incid, id_var
+    INTEGER(KIND=4)               :: istatus
+    INTEGER(KIND=4)               :: iimin, ijmin, ikmin
+    INTEGER(KIND=4)               :: itime, ilog
+    INTEGER(KIND=4)               :: idum
+    REAL(KIND=4)                  :: sf=1., ao=0.       !  Scale factor and add_offset
+    REAL(KIND=4)                  :: spval              !  Missing values
+    LOGICAL                       :: llog=.FALSE. , lsf=.FALSE. , lao=.FALSE.
+    !!---------------------------------------------------------------------
+    IF (PRESENT(kimin) ) THEN
+       iimin=kimin
+    ELSE
+       iimin=1
+    ENDIF
+
+    IF (PRESENT(kjmin) ) THEN
+       ijmin=kjmin
+    ELSE
+       ijmin=1
+    ENDIF
+
+    IF (PRESENT(kkmin) ) THEN
+       ikmin=kkmin
+    ELSE
+       ikmin=1
+    ENDIF
+
+    IF (PRESENT(ktime) ) THEN
+       itime=ktime
+    ELSE
+       itime=1
+    ENDIF
+   
+    ! Must reset the flags to false for every call to getvar
+    llog=.FALSE.
+    lsf=.FALSE.
+    lao=.FALSE.
+    PRINT *,' GETVAR3D '
+    PRINT *,'  ', TRIM(cdfile)
+    PRINT *,'  ', TRIM(cdvar )
+    PRINT *,'    KPI KPJ KPZ ',kpi, kpj, kpz
+
+    CALL ERR_HDL(NF90_OPEN(cdfile,NF90_NOWRITE,incid) )
+    CALL ERR_HDL(NF90_INQ_VARID ( incid, cdvar, id_var) )
+    istart=(/iimin, ijmin, ikmin, itime/)
+    icount=(/kpi,   kpj,   kpz,   1    /)
+
+    spval = getspval ( cdfile, cdvar )
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(incid,id_var,'savelog10')
+    IF (istatus == NF90_NOERR ) THEN
+       ! there is a scale factor for this variable
+       istatus=NF90_GET_ATT(incid,id_var,'savelog10',ilog)
+       IF ( ilog /= 0 ) llog=.TRUE.
+    ENDIF
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(incid,id_var,'scale_factor')
+    IF (istatus == NF90_NOERR ) THEN
+       ! there is a scale factor for this variable
+       istatus=NF90_GET_ATT(incid,id_var,'scale_factor',sf)
+       IF ( sf /= 1. ) lsf=.TRUE.
+    ENDIF
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(incid,id_var,'add_offset')
+    IF (istatus == NF90_NOERR ) THEN
+       ! there is a scale factor for this variable
+       istatus=NF90_GET_ATT(incid,id_var,'add_offset',ao)
+       IF ( ao /= 0.) lao=.TRUE.
+    ENDIF
+
+    istatus=NF90_GET_VAR(incid,id_var,getvar3d, start=istart,count=icount)
+    IF ( istatus /= 0 ) THEN
+       PRINT *,' Problem in getvar3d for ', TRIM(cdvar)
+       CALL ERR_HDL(istatus)
+       STOP
+    ENDIF
+
+    ! Caution : order does matter !
+    IF (lsf )  WHERE (getvar3d /= spval )  getvar3d=getvar3d*sf
+    IF (lao )  WHERE (getvar3d /= spval )  getvar3d=getvar3d + ao
+    IF (llog)  WHERE (getvar3d /= spval )  getvar3d=10**getvar3d
+
+    istatus=NF90_CLOSE(incid)
+
+  END FUNCTION getvar3d
+
+  FUNCTION  getvar3dt (cdfile,cdvar,kk, kpi,kpj,kpt, kimin, kjmin, ktmin )
+    !!---------------------------------------------------------------------
+    !!                  ***  FUNCTION  getvar3d  ***
+    !!
+    !! ** Purpose : Return the 3D REAL variable cdvar(x,y,t), at level kk
+    !!              from cdfile.  kpi,kpj,kpt are the size of the variable
+    !!              subdomain starting point can be specified by kimin, kjmin, ktmin
+    !!
+    !! ** Method  : Use NF90 primitive to read the block of 3D data
+    !!
+    !!---------------------------------------------------------------------
+    CHARACTER(LEN=*),          INTENT(in) :: cdfile
+    CHARACTER(LEN=*),          INTENT(in) :: cdvar
+    INTEGER(KIND=4),           INTENT(in) :: kpi,   kpj,   kk, kpt
+    INTEGER(KIND=4), OPTIONAL, INTENT(in) :: kimin, kjmin, ktmin
+    REAL(KIND=4), DIMENSION(kpi,kpj,kpt)  :: getvar3dt      ! 3D REAL 
+
+    INTEGER(KIND=4), DIMENSION(4) :: istart, icount
+    INTEGER(KIND=4)               :: jt
+    INTEGER(KIND=4)               :: incid, id_var, iid
+    INTEGER(KIND=4)               :: istatus
+    INTEGER(KIND=4)               :: iimin, ijmin, itmin
+    INTEGER(KIND=4)               :: itime, ilog
+    INTEGER(KIND=4)               :: idum
+    REAL(KIND=4)                  :: sf=1., ao=0.       !  Scale factor and add_offset
+    REAL(KIND=4)                  :: spval              !  Missing values
+    LOGICAL                       :: llog=.FALSE. , lsf=.FALSE. , lao=.FALSE.
+    !!---------------------------------------------------------------------
+    IF (PRESENT(kimin) ) THEN
+       iimin=kimin
+    ELSE
+       iimin=1
+    ENDIF
+
+    IF (PRESENT(kjmin) ) THEN
+       ijmin=kjmin
+    ELSE
+       ijmin=1
+    ENDIF
+
+    IF (PRESENT(ktmin) ) THEN
+       itmin=ktmin
+    ELSE
+       itmin=1
+    ENDIF
+
+    ! Must reset the flags to false for every call to getvar
+    llog=.FALSE.
+    lsf=.FALSE.
+    lao=.FALSE.
+    PRINT *,' GETVAR3DT '
+    PRINT *,'  ', TRIM(cdfile)
+    PRINT *,'  ', TRIM(cdvar )
+    PRINT *,'    KPI KPJ KPT, KK ',kpi, kpj, kpt, kk
+
+    CALL ERR_HDL(NF90_OPEN(cdfile,NF90_NOWRITE,incid) )
+    CALL ERR_HDL(NF90_INQ_VARID ( incid, cdvar, id_var) )
+    istatus= NF90_INQUIRE_VARIABLE(incid, id_var, ndims=iid)
+    IF ( iid == 4 ) THEN
+      istart=(/iimin, ijmin, kk, itmin/)
+      icount=(/kpi,   kpj,    1, kpt  /)
+    ELSEIF  ( iid == 3 ) THEN ! assume X Y T ( cannot be X, Z, T nor Y Z T )
+      istart=(/iimin, ijmin, itmin, 1/)
+      icount=(/kpi,   kpj,   kpt  , 1/)
+    ENDIF
+
+    spval = getspval ( cdfile, cdvar )
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(incid,id_var,'savelog10')
+    IF (istatus == NF90_NOERR ) THEN
+       ! there is a scale factor for this variable
+       istatus=NF90_GET_ATT(incid,id_var,'savelog10',ilog)
+       IF ( ilog /= 0 ) llog=.TRUE.
+    ENDIF
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(incid,id_var,'scale_factor')
+    IF (istatus == NF90_NOERR ) THEN
+       ! there is a scale factor for this variable
+       istatus=NF90_GET_ATT(incid,id_var,'scale_factor',sf)
+       IF ( sf /= 1. ) lsf=.TRUE.
+    ENDIF
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(incid,id_var,'add_offset')
+    IF (istatus == NF90_NOERR ) THEN
+       ! there is a scale factor for this variable
+       istatus=NF90_GET_ATT(incid,id_var,'add_offset',ao)
+       IF ( ao /= 0.) lao=.TRUE.
+    ENDIF
+
+    istatus=NF90_GET_VAR(incid,id_var, getvar3dt(:,:,:), start=istart,count=icount)
+    IF ( istatus /= 0 ) THEN
+       PRINT *,' Problem in getvar3dt for ', TRIM(cdvar)
+       CALL ERR_HDL(istatus)
+       STOP
+    ENDIF
+
+    ! Caution : order does matter !
+    IF (lsf )  WHERE (getvar3dt /= spval )  getvar3dt=getvar3dt*sf
+    IF (lao )  WHERE (getvar3dt /= spval )  getvar3dt=getvar3dt + ao
+    IF (llog)  WHERE (getvar3dt /= spval )  getvar3dt=10**getvar3dt
+
+    istatus=NF90_CLOSE(incid)
+
+  END FUNCTION getvar3dt
+
+  FUNCTION  getvar4d (cdfile,cdvar,kpi,kpj,kpz,kpt, kimin, kjmin, kkmin, ktmin )
+    !!---------------------------------------------------------------------
+    !!                  ***  FUNCTION  getvar4d  ***
+    !!
+    !! ** Purpose : Return the 4D REAL variable cdvar(x,y,z,t).
+    !!              kpi,kpj,kpz,kpt are the dimensions of the 4D variable.
+    !!              A subdomain can be specified using kimin, kjmin, kkmin, ktmin
+    !!
+    !! ** Method  : Use NF90 primitive to read the block of 3D data
+    !!
+    !!---------------------------------------------------------------------
+    CHARACTER(LEN=*),          INTENT(in) :: cdfile
+    CHARACTER(LEN=*),          INTENT(in) :: cdvar
+    INTEGER(KIND=4),           INTENT(in) :: kpi,   kpj,   kpz, kpt
+    INTEGER(KIND=4), OPTIONAL, INTENT(in) :: kimin, kjmin, kkmin, ktmin
+    REAL(KIND=4), DIMENSION(kpi,kpj,kpz,kpt) :: getvar4d      ! 3D REAL 
+
+    INTEGER(KIND=4), DIMENSION(4) :: istart, icount
+    INTEGER(KIND=4)               :: incid, id_var, iid
+    INTEGER(KIND=4)               :: istatus
+    INTEGER(KIND=4)               :: iimin, ijmin, ikmin, itmin
+    INTEGER(KIND=4)               :: ilog
+    INTEGER(KIND=4)               :: idum
+    REAL(KIND=4)                  :: sf=1., ao=0.       !  Scale factor and add_offset
+    REAL(KIND=4)                  :: spval              !  Missing values
+    LOGICAL                       :: llog=.FALSE. , lsf=.FALSE. , lao=.FALSE.
+    !!---------------------------------------------------------------------
+    IF (PRESENT(kimin) ) THEN
+       iimin=kimin
+    ELSE
+       iimin=1
+    ENDIF
+
+    IF (PRESENT(kjmin) ) THEN
+       ijmin=kjmin
+    ELSE
+       ijmin=1
+    ENDIF
+
+    IF (PRESENT(kkmin) ) THEN
+       ikmin=kkmin
+    ELSE
+       ikmin=1
+    ENDIF
+
+    IF (PRESENT(ktmin) ) THEN
+       itmin=ktmin
+    ELSE
+       itmin=1
+    ENDIF
+   
+    ! Must reset the flags to false for every call to getvar
+    llog=.FALSE.
+    lsf=.FALSE.
+    lao=.FALSE.
+    PRINT *,' GETVAR4D '
+    PRINT *,'  ', TRIM(cdfile)
+    PRINT *,'  ', TRIM(cdvar )
+    PRINT *,'    KPI KPJ KPZ, KPT ',kpi, kpj, kpz, kpt
+
+    CALL ERR_HDL(NF90_OPEN(cdfile,NF90_NOWRITE,incid) )
+    CALL ERR_HDL(NF90_INQ_VARID ( incid, cdvar, id_var) )
+    istatus= NF90_INQUIRE_VARIABLE(incid, id_var, ndims=iid)
+    IF ( iid == 4 ) THEN
+      istart=(/iimin, ijmin, ikmin, itmin/)
+      icount=(/kpi,   kpj,   kpz,   kpt  /)
+    ELSEIF  ( iid == 3 ) THEN ! assume X Y T ( cannot be X, Z, T nor Y Z T )
+      istart=(/iimin, ijmin, itmin, 1/)
+      icount=(/kpi,   kpj,   kpt,   1/)
+    ENDIF
+
+    spval = getspval ( cdfile, cdvar )
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(incid,id_var,'savelog10')
+    IF (istatus == NF90_NOERR ) THEN
+       ! there is a scale factor for this variable
+       istatus=NF90_GET_ATT(incid,id_var,'savelog10',ilog)
+       IF ( ilog /= 0 ) llog=.TRUE.
+    ENDIF
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(incid,id_var,'scale_factor')
+    IF (istatus == NF90_NOERR ) THEN
+       ! there is a scale factor for this variable
+       istatus=NF90_GET_ATT(incid,id_var,'scale_factor',sf)
+       IF ( sf /= 1. ) lsf=.TRUE.
+    ENDIF
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(incid,id_var,'add_offset')
+    IF (istatus == NF90_NOERR ) THEN
+       ! there is a scale factor for this variable
+       istatus=NF90_GET_ATT(incid,id_var,'add_offset',ao)
+       IF ( ao /= 0.) lao=.TRUE.
+    ENDIF
+
+    istatus=NF90_GET_VAR(incid,id_var,getvar4d, start=istart,count=icount)
+    IF ( istatus /= 0 ) THEN
+       PRINT *,' Problem in getvar4d for ', TRIM(cdvar)
+       CALL ERR_HDL(istatus)
+       STOP
+    ENDIF
+
+    ! Caution : order does matter !
+    IF (lsf )  WHERE (getvar4d /= spval )  getvar4d=getvar4d*sf
+    IF (lao )  WHERE (getvar4d /= spval )  getvar4d=getvar4d + ao
+    IF (llog)  WHERE (getvar4d /= spval )  getvar4d=10**getvar4d
+
+    istatus=NF90_CLOSE(incid)
+
+  END FUNCTION getvar4d
+
 
   FUNCTION  getvarxz (cdfile, cdvar, kj, kpi, kpz, kimin, kkmin, ktime)
     !!-------------------------------------------------------------------------
-    !!                  ***  FUNCTION  getvar  ***
+    !!                  ***  FUNCTION  getvarxz  ***
     !!
     !! ** Purpose : Return the 2D REAL variable x-z slab cvar, from cdfile at j=kj
     !!              kpi,kpz are the  size of the 2D variable
@@ -1701,7 +2165,7 @@ CONTAINS
     ! gdepw(time,z,y_a,x_a)            gdepw_0(t,z)
     !   e3t(time,z,y_a,x_a)            e3t_0(t,z)
     !   e3w(time,z,y_a,x_a)            e3w_0(t,z)
-    istatus=NF90_INQ_VARID ( incid,'e3t_0',id_var)
+    istatus=NF90_INQ_VARID ( incid,'gdept_0',id_var)
     IF ( istatus == NF90_NOERR) THEN
      icount(1)=kk ; icount(3)=1
      SELECT CASE (clvar)
@@ -1715,6 +2179,20 @@ CONTAINS
            clvar='e3w_0'
       END SELECT
     ENDIF
+    istatus=NF90_INQ_VARID ( incid,'gdept_1d',id_var)
+    IF ( istatus == NF90_NOERR) THEN
+     icount(1)=kk ; icount(3)=1
+     SELECT CASE (clvar)
+        CASE ('gdepw') 
+           clvar='gdepw_1d'
+        CASE ('gdept')
+           clvar='gdept_1d'
+        CASE ('e3t')
+           clvar='e3t_1d'
+        CASE ('e3w')
+           clvar='e3w_1d'
+      END SELECT
+    ENDIF
 
     istatus=NF90_INQ_VARID ( incid,clvar,id_var)
     istatus=NF90_GET_VAR(incid,id_var,getvare3,start=istart,count=icount)
@@ -1780,8 +2258,15 @@ CONTAINS
           z2d = pnavlon
        ELSE
           IF ( chkvar ( cdfile, cn_vlon2d )) THEN
-            PRINT *, '... dummy value used!'
-            z2d = 0.
+              IF (chkvar (cdfile, cn_vlon1d) ) THEN
+                PRINT *, '... dummy value used!'
+                z2d = 0.
+              ELSE
+                z2d(:,1) = getvar1d(cdfile, cn_vlon1d, kpi, istatus ) 
+                DO jj=2,kpj
+                  z2d(:,jj) = z2d(:,1)
+                ENDDO
+              ENDIF
           ELSE
             z2d=getvar(cdfile,cn_vlon2d, 1,kpi,kpj)
           ENDIF
@@ -1792,8 +2277,15 @@ CONTAINS
           z2d = pnavlat
        ELSE
           IF ( chkvar ( cdfile, cn_vlat2d )) THEN
-            PRINT *, '... dummy value used!'
-            z2d = 0.
+              IF (chkvar (cdfile, cn_vlat1d) ) THEN
+                PRINT *, '... dummy value used!'
+                z2d = 0.
+              ELSE
+                z2d(1,:) = getvar1d(cdfile, cn_vlat1d, kpj, istatus ) 
+                DO jj=2,kpi
+                  z2d(jj,:) = z2d(1,:)
+                ENDDO
+              ENDIF
           ELSE
             z2d=getvar(cdfile,cn_vlat2d, 1,kpi,kpj)
           ENDIF
@@ -1851,7 +2343,7 @@ CONTAINS
     INTEGER(KIND=4), OPTIONAL,        INTENT(in) :: ktime    ! dimension of ptab
     INTEGER(KIND=4), OPTIONAL,        INTENT(in) :: kwght    ! weight of this variable
 
-    INTEGER(KIND=4)               :: istatus, itime, id_dimunlim
+    INTEGER(KIND=4)               :: istatus, itime, id_dimunlim, inbdim
     INTEGER(KIND=4), DIMENSION(4) :: istart, icount, inldim
     !!----------------------------------------------------------------------
     IF (PRESENT(ktime) ) THEN
@@ -1860,19 +2352,16 @@ CONTAINS
        itime=1
     ENDIF
 
-    ! Look for a unlimited dimension
-    istatus=NF90_INQUIRE(kout, unlimitedDimId = id_dimunlim)
-    inldim(:) = 0
-    istart(:) = 1
-    istatus=NF90_INQUIRE_VARIABLE(kout, kid, dimids = inldim(:) )
+     ! look for unlimited dim (time_counter)
+    istatus=NF90_INQUIRE         (kout, unlimitedDimId=id_dimunlim       )
+    istatus=NF90_INQUIRE_VARIABLE(kout,kid,ndims=inbdim,dimids=inldim(:) )
 
-    IF ( inldim(3) == id_dimunlim)  THEN  ! this is a x,y,t file
-     istart(3)=itime ; istart(4)=1
-    ELSE
-     istart(3)=klev ; istart(4)=itime     ! this is a x,y,z, t file
-    ENDIF
+    !  if the last dim of id_var is time, then adjust the starting point
+    istart(:) = 1    ; icount(:) = 1    ! default
+    icount(1) = kpi  ; icount(2) = kpj  ! in any case
+    IF ( inldim(inbdim) == id_dimunlim ) istart(inbdim) = itime ! assume than last dim is UNLIM
+    IF ( inbdim == 4                   ) istart(3     ) = klev
 
-    icount(:) = 1 ; icount(1) = kpi ; icount(2) = kpj
     istatus=NF90_PUT_VAR(kout,kid, ptab, start=istart,count=icount)
 
     IF (PRESENT(kwght) ) THEN
@@ -1882,7 +2371,6 @@ CONTAINS
 
   END FUNCTION putvarr8
 
-
   INTEGER(KIND=4) FUNCTION putvarr4(kout, kid, ptab, klev, kpi, kpj, ktime, kwght)
     !!---------------------------------------------------------------------
     !!                  ***  FUNCTION putvarr4  ***
@@ -1900,7 +2388,7 @@ CONTAINS
     INTEGER(KIND=4), OPTIONAL,        INTENT(in) :: ktime    ! dimension of ptab
     INTEGER(KIND=4), OPTIONAL,        INTENT(in) :: kwght    ! weight of this variable
 
-    INTEGER(KIND=4)               :: istatus, itime, id_dimunlim
+    INTEGER(KIND=4)               :: istatus, itime, id_dimunlim, inbdim
     INTEGER(KIND=4), DIMENSION(4) :: istart, icount, inldim
     !!----------------------------------------------------------------------
     IF (PRESENT(ktime) ) THEN
@@ -1909,19 +2397,16 @@ CONTAINS
        itime=1
     ENDIF
 
-    ! Look for a unlimited dimension
-    istatus=NF90_INQUIRE(kout, unlimitedDimId = id_dimunlim)
-    inldim(:) = 0
-    istart(:) = 1
-    istatus=NF90_INQUIRE_VARIABLE(kout, kid, dimids = inldim(:) )
+     ! look for unlimited dim (time_counter)
+    istatus=NF90_INQUIRE         (kout, unlimitedDimId=id_dimunlim       )
+    istatus=NF90_INQUIRE_VARIABLE(kout,kid,ndims=inbdim,dimids=inldim(:) )
 
-    IF ( inldim(3) == id_dimunlim)  THEN  ! this is a x,y,t file
-     istart(3)=itime ; istart(4)=1
-    ELSE
-     istart(3)=klev ; istart(4)=itime     ! this is a x,y,z, t file
-    ENDIF
+    !  if the last dim of id_var is time, then adjust the starting point
+    istart(:) = 1    ; icount(:) = 1    ! default
+    icount(1) = kpi  ; icount(2) = kpj  ! in any case
+    IF ( inldim(inbdim) == id_dimunlim ) istart(inbdim) = itime ! assume than last dim is UNLIM
+    IF ( inbdim == 4                   ) istart(3     ) = klev
 
-    icount(:) = 1 ; icount(1) = kpi ; icount(2) = kpj
     istatus=NF90_PUT_VAR(kout,kid, ptab, start=istart,count=icount)
 
     IF (PRESENT(kwght) ) THEN
@@ -1932,6 +2417,50 @@ CONTAINS
   END FUNCTION putvarr4
 
 
+  INTEGER(KIND=4) FUNCTION putvare3(kout, kid, ptab, kmax, cd_vert, ktime, kwght)
+    !!---------------------------------------------------------------------
+    !!                  ***  FUNCTION putvarr4  ***
+    !!            
+    !! ** Purpose : copy a 2D level of ptab in already open file kout, 
+    !!              using variable kid
+    !!
+    !! ** Method  : this corresponds to the generic function putvar with r4 arg.
+    !!----------------------------------------------------------------------
+    INTEGER(KIND=4),                  INTENT(in) :: kout     ! ncid of output file
+    INTEGER(KIND=4),                  INTENT(in) :: kid      ! varid of output variable
+    REAL(KIND=4), DIMENSION(kmax),    INTENT(in) :: ptab     ! 1D array to write in file 
+    INTEGER(KIND=4),                  INTENT(in) :: kmax     ! number of level in file
+    CHARACTER(LEN=*),                 INTENT(in) :: cd_vert  ! dummy var to indicate vertical profile
+    INTEGER(KIND=4), OPTIONAL,        INTENT(in) :: ktime    ! 
+    INTEGER(KIND=4), OPTIONAL,        INTENT(in) :: kwght    ! weight of this variable
+
+    INTEGER(KIND=4)               :: istatus, itime, id_dimunlim, inbdim
+    INTEGER(KIND=4), DIMENSION(4) :: istart, icount, inldim
+    !!----------------------------------------------------------------------
+    IF (PRESENT(ktime) ) THEN
+       itime=ktime
+    ELSE
+       itime=1
+    ENDIF
+
+     ! look for unlimited dim (time_counter)
+    istatus=NF90_INQUIRE         (kout, unlimitedDimId=id_dimunlim       )
+    istatus=NF90_INQUIRE_VARIABLE(kout,kid,ndims=inbdim,dimids=inldim(:) )
+
+    !  if the last dim of id_var is time, then adjust the starting point
+    istart(:) = 1    ; icount(:) = 1    ! default
+    icount(1) = 1  ; icount(2) = 1  ; icount(3) = kmax ! in any case
+    IF ( inldim(inbdim) == id_dimunlim ) istart(inbdim) = itime ! assume than last dim is UNLIM
+
+    istatus=NF90_PUT_VAR(kout,kid, ptab, start=istart,count=icount)
+
+    IF (PRESENT(kwght) ) THEN
+      istatus=NF90_PUT_ATT(kout, kid, 'iweight', kwght)
+    ENDIF
+    putvare3=istatus
+
+  END FUNCTION putvare3
+
   INTEGER(KIND=4) FUNCTION putvari2(kout, kid, ktab, klev, kpi, kpj, ktime, kwght)
     !!---------------------------------------------------------------------
     !!                  ***  FUNCTION putvari2  ***
@@ -1949,7 +2478,7 @@ CONTAINS
     INTEGER(KIND=4), OPTIONAL,           INTENT(in) :: ktime    ! dimension of ktab
     INTEGER(KIND=4), OPTIONAL,           INTENT(in) :: kwght    ! weight of this variable
 
-    INTEGER(KIND=4)               :: istatus, itime, id_dimunlim
+    INTEGER(KIND=4)               :: istatus, itime, id_dimunlim, inbdim
     INTEGER(KIND=4), DIMENSION(4) :: istart, icount, inldim
     !!----------------------------------------------------------------------
     IF (PRESENT(ktime) ) THEN
@@ -1958,19 +2487,16 @@ CONTAINS
        itime=1
     ENDIF
 
-    ! Look for a unlimited dimension
-    istatus=NF90_INQUIRE(kout, unlimitedDimId = id_dimunlim)
-    inldim(:) = 0
-    istart(:) = 1
-    istatus=NF90_INQUIRE_VARIABLE(kout, kid, dimids = inldim(:) )
+     ! look for unlimited dim (time_counter)
+    istatus=NF90_INQUIRE         (kout, unlimitedDimId=id_dimunlim       )
+    istatus=NF90_INQUIRE_VARIABLE(kout,kid,ndims=inbdim,dimids=inldim(:) )
 
-    IF ( inldim(3) == id_dimunlim)  THEN  ! this is a x,y,t file
-     istart(3)=itime ; istart(4)=1
-    ELSE
-     istart(3)=klev ; istart(4)=itime     ! this is a x,y,z, t file
-    ENDIF
+    !  if the last dim of id_var is time, then adjust the starting point
+    istart(:) = 1    ; icount(:) = 1    ! default
+    icount(1) = kpi  ; icount(2) = kpj  ! in any case
+    IF ( inldim(inbdim) == id_dimunlim ) istart(inbdim) = itime ! assume than last dim is UNLIM
+    IF ( inbdim == 4                   ) istart(3     ) = klev
 
-    icount(:) = 1 ; icount(1) = kpi ; icount(2) = kpj
     istatus=NF90_PUT_VAR(kout,kid, ktab, start=istart,count=icount)
 
     IF (PRESENT(kwght) ) THEN
@@ -1997,9 +2523,9 @@ CONTAINS
     REAL(KIND=4), DIMENSION(kpi,kpj), INTENT(in) :: ptab        ! 2D REAL 4 holding variable field at klev
     INTEGER(KIND=4), OPTIONAL,        INTENT(in) :: kwght        ! weight of this variable
 
-    INTEGER(KIND=4), DIMENSION(4) :: istart, icount, inldim
-    INTEGER(KIND=4) :: incid, id_var, id_dimunlim
+    INTEGER(KIND=4) :: incid, id_var, id_dimunlim, inbdim
     INTEGER(KIND=4) :: istatus, ilev, iimin, ijmin, itime
+    INTEGER(KIND=4), DIMENSION(4) :: istart, icount, inldim
     !!----------------------------------------------------------------------
     ilev  = 1 ; IF (PRESENT(klev ) ) ilev  = klev
     iimin = 1 ; IF (PRESENT(kimin) ) iimin = kimin
@@ -2008,16 +2534,18 @@ CONTAINS
 
     istatus=NF90_OPEN(cdfile,NF90_WRITE,incid)
     istatus=NF90_INQ_VARID(incid,cdvar,id_var)
-    !! look for eventual unlimited dim (time_counter)
-    istatus=NF90_INQUIRE(incid, unlimitedDimId=id_dimunlim)
-    
-    inldim=0
-    istatus=NF90_INQUIRE_VARIABLE(incid, id_var,dimids=inldim(:) )
+     ! look for unlimited dim (time_counter)
+    istatus=NF90_INQUIRE         (incid,    unlimitedDimId=id_dimunlim       )
+    istatus=NF90_INQUIRE_VARIABLE(incid,id_var,ndims=inbdim,dimids=inldim(:) )
 
-    ! if the third dim of id_var is time, then adjust the starting point 
-    ! to take ktime into account (case XYT file)
-    IF ( inldim(3) == id_dimunlim)  THEN ; ilev=itime ; itime=1 ; ENDIF
-    istatus=NF90_PUT_VAR(incid,id_var, ptab,start=(/iimin,ijmin,ilev,itime/), count=(/kpi,kpj,1,1/) )
+    !  if the last dim of id_var is time, then adjust the starting point
+    istart(:) = 1     ; icount(:) = 1    ! default
+    istart(1) = iimin ; istart(2) = ijmin
+    icount(1) = kpi   ; icount(2) = kpj  ! in any case
+    IF ( inldim(inbdim) == id_dimunlim ) istart(inbdim) = itime ! assume than last dim is UNLIM
+    IF ( inbdim == 4                   ) istart(3     ) = ilev
+
+    istatus=NF90_PUT_VAR(incid,id_var, ptab,start=istart, count=icount )
 
     IF (PRESENT(kwght)) THEN
       istatus=NF90_PUT_ATT(incid,id_var,'iweight',kwght)
@@ -2040,13 +2568,13 @@ CONTAINS
     !!----------------------------------------------------------------------
     INTEGER(KIND=4),              INTENT(in) :: kout             ! ncid of output file
     INTEGER(KIND=4),              INTENT(in) :: kid              ! varid of output variable
-    REAL(KIND=4), DIMENSION(kpj), INTENT(in) :: ptab             ! 2D array to write in file
+    REAL(KIND=4), DIMENSION(:),   INTENT(in) :: ptab             ! 1D array to write in file (x-z or y-z )
     INTEGER(KIND=4),              INTENT(in) :: klev             ! level at which ptab will be written
     INTEGER(KIND=4),              INTENT(in) :: kpi, kpj         ! dimension of ptab
     INTEGER(KIND=4), OPTIONAL,    INTENT(in) :: ktime            ! time to write
 
-    INTEGER(KIND=4)               :: istatus, itime, ilev, id_dimunlim
-    INTEGER(KIND=4), DIMENSION(4) :: istart, icount,inldim
+    INTEGER(KIND=4)               :: istatus, itime, ilev, id_dimunlim, inbdim
+    INTEGER(KIND=4), DIMENSION(4) :: istart, icount, inldim
     !!----------------------------------------------------------------------
     ilev=klev
     IF (PRESENT(ktime) ) THEN
@@ -2056,15 +2584,16 @@ CONTAINS
     ENDIF
 
      ! look for unlimited dim (time_counter)
-    istatus=NF90_INQUIRE(kout, unlimitedDimId=id_dimunlim)
-    inldim=0
-    istatus=NF90_INQUIRE_VARIABLE(kout,kid,dimids=inldim(:) )
+    istatus=NF90_INQUIRE         (kout, unlimitedDimId=id_dimunlim       )
+    istatus=NF90_INQUIRE_VARIABLE(kout,kid,ndims=inbdim,dimids=inldim(:) )
 
     !  if the third dim of id_var is time, then adjust the starting point 
     !  to take ktime into account (case XYT file)
-    IF ( inldim(3) == id_dimunlim)  THEN ; ilev=itime ; itime=1 ; ENDIF
-    istart(:) = 1 ; istart(3)=ilev ; istart(4)=itime
-    icount(:) = 1 ; icount(1) = kpi ; icount(2) = kpj
+    istart(:) = 1    ; icount(:) = 1    ! default 
+    icount(1) = kpi  ; icount(2) = kpj  ! in any case
+    IF ( inldim(inbdim) == id_dimunlim ) istart(inbdim) = itime ! assume than last dim is UNLIM
+    IF ( inbdim == 4                   ) istart(3) = klev
+
     istatus=NF90_PUT_VAR(kout,kid, ptab, start=istart,count=icount)
     putvarzo=istatus
 
@@ -2133,7 +2662,7 @@ CONTAINS
 
   END FUNCTION reputvar1d4
 
-  INTEGER(KIND=4) FUNCTION putvar0dt(kout, kvarid, pvalue, ktime)
+  INTEGER(KIND=4) FUNCTION putvar0dt(kout, kid, pvalue, ktime)
     !!---------------------------------------------------------------------
     !!                  ***  FUNCTION putvar0dt  ***
     !!
@@ -2143,26 +2672,38 @@ CONTAINS
     !!
     !!----------------------------------------------------------------------
     INTEGER(KIND=4),              INTENT(in) :: kout   ! ncid of output file
-    INTEGER(KIND=4),              INTENT(in) :: kvarid ! id of the variable
+    INTEGER(KIND=4),              INTENT(in) :: kid    ! id of the variable
     REAL(KIND=4), DIMENSION(1,1), INTENT(in) :: pvalue ! single value to write in file
     INTEGER(KIND=4), OPTIONAL,    INTENT(in) :: ktime  ! time frame to write
 
     INTEGER(KIND=4) :: istatus
     INTEGER(KIND=4) :: itime
+    INTEGER(KIND=4) :: id_dimunlim, inbdim
+    INTEGER(KIND=4), DIMENSION(4) :: inldim, istart, icount
     !!----------------------------------------------------------------------
     IF (PRESENT(ktime) ) THEN
       itime = ktime
     ELSE
       itime = 1
+    ENDIF 
+    
+     ! look for unlimited dim (time_counter)
+    istatus=NF90_INQUIRE(kout, unlimitedDimId=id_dimunlim)
+    istatus=NF90_INQUIRE_VARIABLE(kout,kid,ndims=inbdim,dimids=inldim(:) )
+
+    istart(:) = 1
+    icount(:) = 1
+    IF ( inldim(inbdim) == id_dimunlim ) THEN ! var has an unlimited dim
+       istart(inbdim) = itime ! assume than last dim is UNLIM 
     ENDIF
 
-    istatus=NF90_PUT_VAR(kout, kvarid, pvalue, start=(/1,1,itime/), count=(/1,1,1/) )
+    istatus=NF90_PUT_VAR(kout, kid, pvalue, start=istart, count=icount )
 
     putvar0dt=istatus
 
   END FUNCTION putvar0dt
 
-  INTEGER(KIND=4) FUNCTION putvar0ds(kout, kvarid, pvalue, ktime)
+  INTEGER(KIND=4) FUNCTION putvar0ds(kout, kid, pvalue, ktime)
     !!---------------------------------------------------------------------
     !!                  ***  FUNCTION putvar0ds  ***
     !!
@@ -2172,12 +2713,15 @@ CONTAINS
     !!
     !!----------------------------------------------------------------------
     INTEGER(KIND=4),              INTENT(in) :: kout   ! ncid of output file
-    INTEGER(KIND=4),              INTENT(in) :: kvarid ! id of the variable
+    INTEGER(KIND=4),              INTENT(in) :: kid    ! id of the variable
     REAL(KIND=4),                 INTENT(in) :: pvalue ! single value to write in file
     INTEGER(KIND=4), OPTIONAL,    INTENT(in) :: ktime  ! time frame to write
 
     INTEGER(KIND=4) :: istatus
     INTEGER(KIND=4) :: itime
+    INTEGER(KIND=4) :: id_dimunlim, inbdim
+    INTEGER(KIND=4), DIMENSION(4) :: inldim, istart, icount
+
     REAL(KIND=4), DIMENSION(1,1)             :: ztab   ! dummy array for PUT_VAR
     !!----------------------------------------------------------------------
     IF (PRESENT(ktime) ) THEN
@@ -2185,16 +2729,24 @@ CONTAINS
     ELSE
       itime = 1
     ENDIF
+
+     ! look for unlimited dim (time_counter)
+    istatus=NF90_INQUIRE(kout, unlimitedDimId=id_dimunlim)
+    istatus=NF90_INQUIRE_VARIABLE(kout,kid,ndims=inbdim,dimids=inldim(:) )
+
+    istart(:) = 1
+    icount(:) = 1
+    IF ( inldim(inbdim) == id_dimunlim ) THEN ! var has an unlimited dim
+       istart(inbdim) = itime ! assume than last dim is UNLIM 
+    ENDIF
     ztab = pvalue
 
-    istatus=NF90_PUT_VAR(kout, kvarid, ztab, start=(/1,1,itime/), count=(/1,1,1/) )
+    istatus=NF90_PUT_VAR(kout, kid, ztab, start=istart, count=icount )
 
     putvar0ds=istatus
 
   END FUNCTION putvar0ds
 
-
-
   INTEGER(KIND=4) FUNCTION closeout(kout)
     !!---------------------------------------------------------------------
     !!                  ***  FUNCTION closeout  ***
@@ -2238,13 +2790,13 @@ CONTAINS
     IF (kstatus /=  NF90_NOERR ) THEN
        PRINT *, 'ERROR in NETCDF routine, status=',kstatus
        PRINT *,NF90_STRERROR(kstatus)
-       STOP
+       STOP 1
     END IF
 
   END SUBROUTINE ERR_HDL
 
 
-  SUBROUTINE gettimeseries (cdfile, cdvar, kilook, kjlook, klev)
+  SUBROUTINE gettimeseries (cdfile, cdvar, kilook, kjlook, klev, ldncdf)
     !!---------------------------------------------------------------------
     !!                  ***  ROUTINE gettimeseries  ***
     !!
@@ -2255,6 +2807,7 @@ CONTAINS
     CHARACTER(LEN=*),          INTENT(in) :: cdfile, cdvar
     INTEGER(KIND=4),           INTENT(in) :: kilook,kjlook
     INTEGER(KIND=4), OPTIONAL, INTENT(in) :: klev
+    LOGICAL,         OPTIONAL, INTENT(in) :: ldncdf
 
     INTEGER(KIND=4)                         :: jt, jk
     INTEGER(KIND=4)                         :: iint
@@ -2264,6 +2817,8 @@ CONTAINS
     REAL(KIND=4), DIMENSION(:), ALLOCATABLE :: ztime, zval
     REAL(KIND=4)                            :: ztmp  
     REAL(KIND=4)                            :: zao=0., zsf=1.0   !: add_offset, scale_factor
+    CHARACTER(LEN=256)                      :: clname
+    LOGICAL                                 :: ll_netcdf=.false.
     !!----------------------------------------------------------------------
     ! Klev can be used to give the model level we want to look at
     IF ( PRESENT(klev) ) THEN
@@ -2272,6 +2827,13 @@ CONTAINS
        jk=1
     ENDIF
 
+    IF ( PRESENT(ldncdf) ) THEN
+       ll_netcdf=ldncdf
+    ELSE
+       ll_netcdf=.false.
+    ENDIF
+
+
     ! Open cdf dataset
     istatus=NF90_OPEN(cdfile,NF90_NOWRITE,incid)
 
@@ -2316,6 +2878,10 @@ CONTAINS
     ENDDO
 
     istatus=NF90_CLOSE(incid)
+    IF ( ll_netcdf )  THEN
+      WRITE (clname,'("probe_",i4.4,"_",i4.4,"_",a,".nc")') kilook, kjlook, TRIM(cdvar)
+    ENDIF
+    ! not finished ...
 
   END SUBROUTINE gettimeseries
 
@@ -2417,7 +2983,178 @@ CONTAINS
 
   END FUNCTION Get_Env
 
+  FUNCTION GetNcFile (cd_file)
+    !!---------------------------------------------------------------------
+    !!                  ***  FUNCTION GetNcFile  ***
+    !!
+    !! ** Purpose :  fills in the ncfile  structure corresponding to the file
+    !!               given in argument 
+    !!
+    !! ** Method  :  Use NF90 function to get the ad-hoc information 
+    !!
+    !!----------------------------------------------------------------------
+    CHARACTER(LEN=*), INTENT(in) :: cd_file
+    TYPE(ncfile)                 :: GetNcFile
+
+    INTEGER(KIND=4) :: jvar, jdim                      ! loop index
+    INTEGER(KIND=4) :: ierr, idx, idy, idz, idt, idb   ! error status and dimids
+    !!----------------------------------------------------------------------
+    GetNcFile%c_fnam = cd_file
+    ierr = NF90_OPEN(cd_file, NF90_NOWRITE, GetNcFile%ncid )
+    ierr = NF90_INQUIRE(GetNcFile%ncid, nDimensions    = GetNcFile%ndims,  &
+         &                              nVariables     = GetNcFile%nvars,  &
+         &                              nAttributes    = GetNcFile%natts,  &
+         &                              unlimitedDimId = GetNcFile%iunlim  )
+    ALLOCATE (GetNcFile%nvdim   (GetNcFile%nvars) )
+    ALLOCATE (GetNcFile%nvid    (GetNcFile%nvars) )
+    ALLOCATE (GetNcFile%c_vnam  (GetNcFile%nvars) )
+    ALLOCATE (GetNcFile%nvatt   (GetNcFile%nvars) )
+    ALLOCATE (GetNcFile%itype   (GetNcFile%nvars) )
+    ALLOCATE (GetNcFile%c_dnam  (GetNcFile%ndims) )
+    ALLOCATE (GetNcFile%nlen    (GetNcFile%ndims) )
+    ALLOCATE (GetNcFile%idimids (GetNcFile%nvars,GetNcFile%ndims) )
+
+    ! Look for dimensions
+    DO jdim = 1, GetNcFile%ndims
+       ierr = NF90_INQUIRE_DIMENSION(GetNcFile%ncid,jdim,                 &
+            &                         name   = GetNcFile%c_dnam(jdim),    &
+            &                         len    = GetNcFile%nlen  (jdim) )
+    ENDDO
+    ! Look for variables
+    DO jvar = 1, GetNcFile%nvars
+       ierr = NF90_INQUIRE_VARIABLE (GetNcFile%ncid, jvar,                &
+            &                         name   = GetNcFile%c_vnam(jvar),    &
+            &                         xtype  = GetNcFile%itype(jvar),     &
+            &                         ndims  = GetNcFile%nvdim(jvar),     &
+            &                         dimids = GetNcFile%idimids(jvar,:), &
+            &                         nAtts  = GetNcFile%nvatt(jvar),     &
+            &                         contiguous = GetNcFile%lconti(jvar),   &
+            &                         chunksizes = GetNcFile%ichunk(jvar,:), &
+            &                         deflate_level = GetNcFile%ideflat(jvar)      )
+    END DO
+    ! Look for attributes
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_number_total'   , GetNcFile%number_total       )
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_number      '   , GetNcFile%number             )
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_dimensions_ids' , GetNcFile%idimensions_ids(:) )
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_size_global'    , GetNcFile%isize_global(:)    )
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_size_local'     , GetNcFile%isize_local(:)     )
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_position_first' , GetNcFile%iposition_first(:) )
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_position_last'  , GetNcFile%iposition_last(:)  )
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_halo_size_start', GetNcFile%ihalo_size_start(:))
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_halo_size_end'  , GetNcFile%ihalo_size_end(:)  )
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_type'           , GetNcFile%c_type             )
+
+    ! NOTE : for recombined files, no more DOMAIN attributes !!!
+    ! DOMAIN_dimensions_ids gives ids for x, y 
+    idx = GetNcFile%idimensions_ids(1)
+    idy = GetNcFile%idimensions_ids(2)
+    ! time is unlimited dim
+    idt = GetNcFile%iunlim
+
+    ! try to infer size of the domain assuming some basis:
+    ! (1) 2D var are (x,y)
+    ! (2) time dim is unlimited
+    ! (3) allowed shape of var : x,y ; x,y,t ; x,y,z,t  ; x,y,z   ; t   ; z 
+
+    ! Look for x y z t tbound dim id
+    idx=-1 ; idy=-1 ; idz=-1 ; idt=-1 ; idb=-1
+
+    DO jvar = 1, GetNcFile%nvars
+       GetNcFile%nvid(jvar) = jvar
+       IF ( GetNcFile%nvdim(jvar) == 2 ) THEN  
+          IF ( GetNcFile%idimids(jvar,2) == GetNcFile%iunlim ) THEN  ! catch a time_bounds, time_counter var
+            idb = GetNcFile%idimids(jvar,1)
+          ELSE
+          idx = GetNcFile%idimids(jvar,1) 
+          idy = GetNcFile%idimids(jvar,2) 
+          ENDIF
+       ELSE IF ( GetNcFile%nvdim(jvar) == 3 ) THEN 
+          idx = GetNcFile%idimids(jvar,1) 
+          idy = GetNcFile%idimids(jvar,2) 
+          IF ( GetNcFile%idimids(jvar,3) == GetNcFile%iunlim ) THEN
+             idt = GetNcFile%idimids(jvar,3) 
+          ELSE
+             idz = GetNcFile%idimids(jvar,3) 
+          ENDIF
+       ELSE IF ( GetNcFile%nvdim(jvar) == 4 ) THEN
+          idx = GetNcFile%idimids(jvar,1)  
+          idy = GetNcFile%idimids(jvar,2)  
+          idz = GetNcFile%idimids(jvar,3)  
+          IF ( GetNcFile%idimids(jvar,4) /= GetNcFile%iunlim ) THEN
+             PRINT *, ' 4D variables must have an unlimited time dimension ...'
+             PRINT *, ' Cannot process this file :', TRIM(cd_file)
+             STOP
+          ENDIF
+          idt = GetNcFile%idimids(jvar,4) 
+       ENDIF
+    END DO
+
+    GetNcFile%idx=idx
+    GetNcFile%idy=idy
+    GetNcFile%idz=idz
+    GetNcFile%idt=idt
+    GetNcFile%idb=idb
+
+    IF ( idx == -1 .OR. idy == -1 ) THEN 
+       PRINT *, ' ERROR : no x, y dimensions found'
+       STOP
+    ENDIF
 
+    ! get dimensions
+    GetNcFile%npi=0 ; GetNcFile%npj=0 ; GetNcFile%npk=0 ; GetNcFile%npt=0 ; GetNcFile%npb=0
+
+    ierr = NF90_INQUIRE_DIMENSION( GetNcFile%ncid, idx,         &
+         &                        name = GetNcFile%c_dnam(idx), &
+         &                        len  = GetNcFile%npi          )
+    GetNcFile%nlen(idx) = GetNcFile%npi
+    ierr = NF90_INQUIRE_DIMENSION( GetNcFile%ncid, idy,         &
+         &                        name = GetNcFile%c_dnam(idy), &
+         &                        len  = GetNcFile%npj          )
+    GetNcFile%nlen(idy) = GetNcFile%npj
+
+    IF ( idz /= -1 ) THEN
+       ierr = NF90_INQUIRE_DIMENSION( GetNcFile%ncid, idz,         &
+            &                        name = GetNcFile%c_dnam(idz), &
+            &                        len  = GetNcFile%npk          )
+       GetNcFile%nlen(idz) = GetNcFile%npk
+    ENDIF
+
+    IF ( idt /= -1 ) THEN
+       ierr = NF90_INQUIRE_DIMENSION( GetNcFile%ncid, idt,         &
+            &                        name = GetNcFile%c_dnam(idt), &
+            &                        len  = GetNcFile%npt          )
+       GetNcFile%nlen(idt) = GetNcFile%npt
+    ENDIF
+
+    IF ( idb /= -1 ) THEN
+       ierr = NF90_INQUIRE_DIMENSION( GetNcFile%ncid, idb,         &
+            &                        name = GetNcFile%c_dnam(idb), &
+            &                        len  = GetNcFile%npb          )
+       GetNcFile%nlen(idb) = GetNcFile%npb
+    ENDIF
+    ! fill in DOMAIN attributes 
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_number_total'   , GetNcFile%number_total       )
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_number      '   , GetNcFile%number             )
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_dimensions_ids' , GetNcFile%idimensions_ids(:) )
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_size_global'    , GetNcFile%isize_global(:)    )
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_size_local'     , GetNcFile%isize_local(:)     )
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_position_first' , GetNcFile%iposition_first(:) )
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_position_last'  , GetNcFile%iposition_last(:)  )
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_halo_size_start', GetNcFile%ihalo_size_start(:))
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_halo_size_end'  , GetNcFile%ihalo_size_end(:)  )
+    ierr = NF90_GET_ATT (GetNcFile%ncid, NF90_GLOBAL, 'DOMAIN_type'           , GetNcFile%c_type             )
+
+    ! CORRECT for Halo :
+    GetNcfile%isize_local(:)     = GetNcfile%isize_local(:)     - GetNcFile%ihalo_size_start(:) - GetNcFile%ihalo_size_end(:)
+    GetNcFile%iposition_first(:) = GetNcFile%iposition_first(:) + GetNcFile%ihalo_size_start(:)
+    GetNcFile%iposition_last(:)  = GetNcFile%iposition_last(:)  - GetNcFile%ihalo_size_end(:)
+
+    GetNcFile%npi       = GetNcfile%isize_local(1)
+    GetNcFile%npj       = GetNcfile%isize_local(2)
+    GetNcFile%nlen(idx) = GetNcFile%npi
+    GetNcFile%nlen(idy) = GetNcFile%npj
+
+  END FUNCTION GetNcFile
 
 END MODULE cdfio
 
diff --git a/src/cdfisf_fill.f90 b/src/cdfisf_fill.f90
new file mode 100644
index 0000000..fc0acf0
--- /dev/null
+++ b/src/cdfisf_fill.f90
@@ -0,0 +1,244 @@
+PROGRAM cdfisf_fill
+  !!======================================================================
+  !!                     ***  PROGRAM  cdfisf_fill  ***
+  !!=====================================================================
+  !!  ** Purpose : Build a file containing one value for each closed pools
+  !!               seeded by a list of points.
+  !!
+  !!  ** Method  : flood filling algorithm
+  !!               
+  !! History : 3.0  : 04/2014  : Pierre Mathiot 
+  !!----------------------------------------------------------------------
+  !!----------------------------------------------------------------------
+  USE cdfio 
+  USE modcdfnames
+  USE modutils
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2014
+  !! $Id$
+  !! Copyright (c) 2010, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!-----------------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)                               :: jisf               ! dummy loop integer 
+  INTEGER(KIND=4)                               :: ierr, ipos         ! working integer
+  INTEGER(KIND=4)                               :: narg, iargc, ijarg ! browsing command line
+  INTEGER(KIND=4)                               :: npiglo, npjglo     ! size of the domain
+  INTEGER(KIND=4)                               :: npk, npt, nisf     ! size of the domain
+  INTEGER(KIND=4)                               :: iunit=10           ! file unit for txt input file
+  INTEGER(KIND=4)                               :: iunitu=11          ! file unit for txt output file
+  INTEGER(KIND=4)                               :: ncout              ! ncid of output files
+  INTEGER(KIND=4)                               :: iiseed, ijseed
+  INTEGER(KIND=4)                               :: ifill
+  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: ipk                ! arrays of vertical level for each var
+  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_varout          ! varid's of average vars
+  INTEGER(KIND=2), DIMENSION(:,:),  ALLOCATABLE :: itab
+
+  REAL(KIND=4)                                  :: rlon, rlat         ! longitude and latitude of one point in ISF
+  REAL(KIND=4)                                  :: rdraftmin, rdraftmax
+  REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: dtab
+
+  CHARACTER(LEN=256)                            :: cf_in              ! input file name
+  CHARACTER(LEN=256)                            :: cf_isflist         ! input file name (txt)
+  CHARACTER(LEN=256)                            :: cf_isflistup       ! output file name (update of input, with draftmin/max
+  CHARACTER(LEN=256)                            :: cf_out='fill.nc'   ! output file for average
+  CHARACTER(LEN=256)                            :: cv_dep             ! depth dimension name
+  CHARACTER(LEN=256)                            :: cv_in              ! depth dimension name
+  CHARACTER(LEN=256)                            :: cdum               ! dummy string argument
+
+  TYPE (variable), DIMENSION(:),    ALLOCATABLE :: stypvar            ! attributes for average values
+  LOGICAL                                       :: lnc4 = .FALSE.     ! flag for netcdf4 chunk and deflation
+
+  !!----------------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  narg= iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage : cdfisf_fill  -f ISF-file -v ISF-var -l ISF-list [-nc4 ] [-o OUT-file]'
+     PRINT *,'      '
+     PRINT *,'     PURPOSE : Build a nc file with a single value for each pool around a list'
+     PRINT *,'               of given point. A warning is given when neighbouring ice-shelves'
+     PRINT *,'               cannot be discriminated (no gap in between). In this case, hand'
+     PRINT *,'               edit on the ISF-file is required.'
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS : '
+     PRINT *,'         -f ISF-file : netcdf file  which contains the ice shelf draft variable'
+     PRINT *,'                     (mesh_zgr is OK). It is used as a mask, only.'
+     PRINT *,'         -v ISF-var  : variable name corresponding to the ice shelf draft or '
+     PRINT *,'                      ice shelf level'
+     PRINT *,'         -l ISF-list : text file containing at least the following information: '
+     PRINT *,'                 1  NAME    LON  LAT I  J '
+     PRINT *,'                 ...             '
+     PRINT *,'                 i  NAMEi   LON  LAT I  J '
+     PRINT *,'                 ...             '
+     PRINT *,'                 EOF             '
+     PRINT *,'                 No NAME  X    Y   I  J '
+     PRINT *,'      '
+     PRINT *,'     OPTIONS : '
+     PRINT *,'          -nc4 : use NetCDF4 chunking and deflation for the output'
+     PRINT *,'          -o OUT-file : specify the name of the output file instead of ',TRIM(cf_out)
+     PRINT *,'                 This file will be one of the input file for cdfmkforcingisf '
+     PRINT *,'                 as the ISF-fill_file '
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'              netcdf file : fill.nc '
+     PRINT *,'              variable : sofillvar contains for all points in ice shelf NAME '
+     PRINT *,'                         the value -i (negative value)'
+     PRINT *,'              text file : <ISF-list>_zmin_zmax.txt '
+     PRINT *,'                        this output file is similar to <ISF-list> but updated'
+     PRINT *,'                        with the minimum and maximul value of ice-draft for '
+     PRINT *,'                        each shelf.'
+     PRINT *,'      '
+     PRINT *,'     SEE ALSO : '
+     PRINT *,'           cdfisf_forcing,  cdfisf_rnf '
+     PRINT *,'      '
+     STOP
+  ENDIF
+
+  ijarg = 1
+  DO WHILE ( ijarg <= narg )
+     CALL getarg(ijarg, cdum ) ; ijarg = ijarg + 1 
+     SELECT CASE ( cdum)
+     CASE ( '-f' ) ; CALL getarg(ijarg, cf_in      ) ; ijarg = ijarg + 1
+     CASE ( '-v' ) ; CALL getarg(ijarg, cv_in      ) ; ijarg = ijarg + 1
+     CASE ( '-l' ) ; CALL getarg(ijarg, cf_isflist ) ; ijarg = ijarg + 1
+     CASE ( '-o' ) ; CALL getarg(ijarg, cf_out     ) ; ijarg = ijarg + 1
+     CASE ('-nc4') ; lnc4=.TRUE.
+     CASE DEFAULT
+        PRINT *, ' Option ', TRIM(cdum),' not understood'
+        STOP
+     END SELECT
+  ENDDO
+
+  IF ( chkfile (cf_in) .OR. chkfile (cf_isflist)  ) STOP ! missing file
+
+  ipos = INDEX(cf_isflist,'.')
+  cdum=cf_isflist(ipos+1:)
+  cf_isflistup=cf_isflist(1:ipos-1)//'_zmin_zmax.'//TRIM(cdum)
+
+  npiglo = getdim (cf_in, cn_x)
+  npjglo = getdim (cf_in, cn_y)
+  npk    = getdim (cf_in, cn_z, cdtrue=cv_dep, kstatus=ierr)
+
+  IF (ierr /= 0 ) THEN
+     npk   = getdim (cf_in, 'z',cdtrue=cv_dep,kstatus=ierr)
+     IF (ierr /= 0 ) THEN
+        npk   = getdim (cf_in,'sigma',cdtrue=cv_dep,kstatus=ierr)
+        IF ( ierr /= 0 ) THEN 
+           npk = getdim (cf_in,'nav_lev',cdtrue=cv_dep,kstatus=ierr)
+           IF ( ierr /= 0 ) THEN 
+              npk = getdim (cf_in,'levels',cdtrue=cv_dep,kstatus=ierr)
+              IF ( ierr /= 0 ) THEN 
+                 PRINT *,' assume file with no depth'
+                 npk=0
+              ENDIF
+           ENDIF
+        ENDIF
+     ENDIF
+  ENDIF
+
+  PRINT *, 'NPIGLO = ', npiglo
+  PRINT *, 'NPJGLO = ', npjglo
+  PRINT *, 'NPK    = ', npk
+
+  ALLOCATE(dtab(npiglo, npjglo))
+  ALLOCATE(itab(npiglo, npjglo))
+
+  ALLOCATE (stypvar(1))
+  ALLOCATE (ipk(1),id_varout(1))
+
+  CALL CreateOutput 
+
+  ! initialize variable
+  dtab(:,:) = 0.d0 
+  ! read ice shelf draft data
+  dtab = getvar(cf_in, cv_in, 1 ,npiglo, npjglo )
+  itab=1
+  WHERE ( dtab <=0 ) itab=0
+  PRINT *, 'Maximum of ISF-draft : ', MAXVAL(dtab),' m'
+
+  ! open isf-list file
+  OPEN(unit=iunit,  file=cf_isflist  , form='formatted', status='old')
+  OPEN(unit=iunitu, file=cf_isflistup, form='formatted'              )
+  ! get total number of isf
+  nisf = 0
+  cdum='XXX'
+  DO WHILE ( TRIM(cdum) /= 'EOF')
+     READ(iunit,*) cdum
+     nisf=nisf+1
+  END DO
+  REWIND(iunit)
+
+  nisf = nisf - 1
+  PRINT *, '   Number of ISF found in file list : ', nisf
+
+  ! loop over each ice shelf
+  DO jisf=1,nisf
+     ! get iiseed, ijseed, ice shelf number ifill
+     READ(iunit,*) ifill, cdum, rlon, rlat, iiseed, ijseed
+     IF (dtab(iiseed, ijseed) < 0 ) THEN
+        PRINT *,'  ==> WARNING: Likely a problem with ',TRIM(cdum)
+        PRINT *,'               check separation with neighbours'
+     ENDIF
+     CALL FillPool2D(iiseed, ijseed,itab, -ifill)
+
+     rdraftmax=MAXVAL(dtab, (itab == -ifill) )
+     rdraftmin=MINVAL(dtab, (itab == -ifill) )
+
+     PRINT *,'Iceshelf : ', TRIM(cdum)
+     PRINT *,'  index  : ', ifill
+     PRINT *,'  code   : ', INT(dtab(iiseed, ijseed ) )
+     PRINT *,'  depmin : ', rdraftmin
+     PRINT *,'  depmax : ', rdraftmax
+     PRINT *,'   '
+     WRITE(iunitu,'(i4,1x,a20,2f9.4,2i5,2f8.1)') jisf,ADJUSTL(cdum),rlon, rlat, iiseed, ijseed,rdraftmin,rdraftmax
+  END DO
+  WRITE(iunitu,'(a)') 'EOF  '
+  WRITE(iunitu,'(a5,a20,2a9,2a5,2a8,a)' ) 'No ','NAME                           ',' X',' Y',' I ',' J ',' Zmin',' Zmax',' FWF'
+
+  CLOSE(iunitu)
+  CLOSE(iunit)
+
+  ! set to 0 all unwanted point (why not .GE. 0.0, I don't know)
+  WHERE (dtab >= 1.d0)
+     dtab = 0.0d0
+  END WHERE
+
+  ierr = putvar(ncout, id_varout(1), itab, 1, npiglo, npjglo)
+
+  ! close file
+  ierr = closeout(ncout)
+
+CONTAINS
+  SUBROUTINE CreateOutput
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE CreateOutput  ***
+    !!
+    !! ** Purpose :  Create the output file. This is done outside the main
+    !!               in order to increase readability of the code. 
+    !!
+    !! ** Method  :  Use global variables, defined in mail 
+    !!----------------------------------------------------------------------
+  ! define new variables for output
+  stypvar(1)%ichunk            = (/npiglo,MAX(1,npjglo/30),1,1 /)
+  stypvar(1)%cname             = 'sofillvar'
+  stypvar(1)%cunits            = 'N/A'
+  stypvar(1)%rmissing_value    = 0.
+  stypvar(1)%valid_min         = -1000.
+  stypvar(1)%valid_max         =  1000.
+  stypvar(1)%clong_name        = 'Fill var'
+  stypvar(1)%cshort_name       = 'sofillvar'
+  stypvar(1)%conline_operation = 'N/A'
+  stypvar(1)%caxis             = 'TYX'
+  stypvar(1)%cprecision        = 'i2'
+  ipk(1) = 1  !  2D
+
+  ! create output file taking the sizes in cf_in
+  ncout  = create      (cf_out,  cf_in,    npiglo, npjglo, npk, cdep=cv_dep, ld_nc4=lnc4)
+  ierr   = createvar   (ncout ,  stypvar,  1,  ipk,    id_varout           , ld_nc4=lnc4)
+  ierr   = putheadervar(ncout,   cf_in,    npiglo, npjglo, npk, cdep=cv_dep             )
+
+  END SUBROUTINE CreateOutput
+
+END PROGRAM cdfisf_fill
diff --git a/src/cdfisf_forcing.f90 b/src/cdfisf_forcing.f90
new file mode 100644
index 0000000..0a95bdf
--- /dev/null
+++ b/src/cdfisf_forcing.f90
@@ -0,0 +1,253 @@
+PROGRAM cdfisf_forcing
+  !!======================================================================
+  !!                     ***  PROGRAM  cdfisf_forcing  ***
+  !!=====================================================================
+  !!  ** Purpose : spread a specified total ice shelf melting over a specific
+  !!               ice shelf melting pattern
+  !!
+  !!  ** Method  : read an ice shelf mask file produce by cdffill, read the
+  !!               integrate melting for each ice shelf and the wanted pattern,
+  !!               then compute the final melting for each ice shelf.
+  !!
+  !! History : 3.0  : 04/2014  : Pierre Mathiot 
+  !!----------------------------------------------------------------------
+  !!----------------------------------------------------------------------
+  USE cdfio 
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id$
+  !! Copyright (c) 2010, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!-----------------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)                               :: jisf               ! dummy loop counter
+  INTEGER(KIND=4)                               :: ierr               ! working integer
+  INTEGER(KIND=4)                               :: narg, iargc, ijarg ! browsing command line
+  INTEGER(KIND=4)                               :: npiglo, npjglo     ! size of the domain
+  INTEGER(KIND=4)                               :: npk, npt, nisf     ! size of the domain
+  INTEGER(KIND=4)                               :: iunit=10           ! id file
+  INTEGER(KIND=4)                               :: ncout              ! ncid of output files
+  INTEGER(KIND=4)                               :: iiseed, ijseed
+  INTEGER(KIND=4)                               :: ifill
+  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: ipk                ! arrays of vertical level for each var
+  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_varout          ! varid's of average vars
+
+  INTEGER(KIND=2), DIMENSION(:,:),  ALLOCATABLE :: ipoolmsk           ! mask for closed pool
+  INTEGER(KIND=2), DIMENSION(:,:),  ALLOCATABLE :: isfindex           ! index of each ISF ( negative integer)
+  INTEGER(KIND=2), DIMENSION(:,:),  ALLOCATABLE :: isfindex_wk        ! index of each ISF 'working variable)
+
+  REAL(KIND=4)                                  :: rdraftmax, rdraftmin ! dummy information in input file
+  REAL(KIND=4)                                  :: rlon, rlat         ! dummy information in input file
+
+  REAL(KIND=8)                                  :: dl_fwf, dsumcoef
+  REAL(KIND=8)                                  :: dfwf
+  REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: dfwfisf2d
+  REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: de12t
+  REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: dl_fwfisf2d, dl_fwfispat
+
+  CHARACTER(LEN=256)                            :: cf_fill            ! input file names
+  CHARACTER(LEN=256)                            :: cf_isflist         ! input file names
+  CHARACTER(LEN=256)                            :: cf_out='isfforcing.nc' ! output file for average
+  CHARACTER(LEN=256)                            :: cf_pat='isfpattern.nc' ! pattern file
+  CHARACTER(LEN=256)                            :: cf_pool='isfpool.nc'   ! pools mask file
+  CHARACTER(LEN=256)                            :: cv_dep             ! depth dimension name
+  CHARACTER(LEN=256)                            :: cv_pat='sowflisf'  ! pattern variable name
+  CHARACTER(LEN=256)                            :: cv_pool='isfpoolmask'! pattern variable name
+  CHARACTER(LEN=256)                            :: cv_fill            ! isf index variable in cf_fill
+  CHARACTER(LEN=256)                            :: cdum               ! dummy string argument
+
+  TYPE (variable), DIMENSION(:),    ALLOCATABLE :: stypvar            ! attributes for average values
+
+  LOGICAL                                       :: lnc4 = .FALSE.     ! flag for netcdf4 chunking and deflation
+  LOGICAL                                       :: lchk = .FALSE.     ! flag for missing values
+
+  !!----------------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  narg= iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage : cdfisf_forcing -f ISF-fill_file  -v ISF-fill_var -l ISF-listfile '
+     PRINT *,'             -m ISF-poolmask [-vm ISF-poolmask_variable] [-p PATTERN-file] '
+     PRINT *,'            [-vp PATTERN-variable] [-nc4] [-o OUT-file ]'
+     PRINT *,'      '
+     PRINT *,'     PURPOSE : '
+     PRINT *,'         Build basal melting rate file used in NEMO ISF when nn_isf=4 '
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS : '
+     PRINT *,'          -f ISF-fill_file : file built by cdfisf_fill (all the ice shelves '
+     PRINT *,'                             are tagged with an id)'
+     PRINT *,'          -v ISF-fill_var  : name of fill variable to use in ISF-fill_file'
+     PRINT *,'          -l ISF-listfile : text file used to build the ISF-fill_file. '
+     PRINT *,'                            Only the last variable on each line is used (GT/y)'
+     PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'          -p PATTERN-file : specify the file use for patterns. '
+     PRINT *,'                            [ default : ',TRIM(cf_pat),' ]'
+     PRINT *,'          -vp PATTERN-variable : specify the name of the pattern variable. '
+     PRINT *,'                            [ default : ',TRIM(cv_pat),' ]'
+     PRINT *,'          -vm ISF-poolmask_variable : specify the name of the variable used '
+     PRINT *,'                 for masking the pools. [ default : ',TRIM(cv_pool),' ]'
+     PRINT *,'          -nc4 : use netcdf4 chunking and deflation'
+     PRINT *,'          -o OUT-file : specify output filename. [ default : ',TRIM(cf_out),' ]'
+     PRINT *,'              '
+     PRINT *,'     REQUIRED FILES : '
+     PRINT *,'           mesh_zgr.nc mesh_hgr.nc,'
+     PRINT *,'           isfpattern.nc (ie reference file used to define the isf melting '
+     PRINT *,'                 pattern), unless -p option is used to give different name.'
+     PRINT *,'      '
+     PRINT *,'     OUTPUT :'
+     PRINT *,'         netcdf file : ', TRIM(cf_out),' unless specified with -o option'
+     PRINT *,'         variable : sofwfisf '
+     PRINT *,'      '
+     PRINT *,'     SEE ALSO : cdfisf_fill, cdfisf_rnf, cdfisf_poolchk'
+     PRINT *,'      '
+     STOP
+  ENDIF
+
+  ijarg = 1
+  DO WHILE ( ijarg <= narg )
+     CALL getarg(ijarg, cdum ) ; ijarg = ijarg + 1
+     SELECT CASE ( cdum)
+     CASE ( '-f' ) ; CALL getarg(ijarg, cf_fill    ) ; ijarg = ijarg + 1
+     CASE ( '-v' ) ; CALL getarg(ijarg, cv_fill    ) ; ijarg = ijarg + 1
+     CASE ( '-l' ) ; CALL getarg(ijarg, cf_isflist ) ; ijarg = ijarg + 1
+     CASE ( '-o' ) ; CALL getarg(ijarg, cf_out     ) ; ijarg = ijarg + 1
+     CASE ( '-p' ) ; CALL getarg(ijarg, cf_pat     ) ; ijarg = ijarg + 1
+     CASE ( '-vp') ; CALL getarg(ijarg, cv_pat     ) ; ijarg = ijarg + 1
+     CASE ( '-m' ) ; CALL getarg(ijarg, cf_pool    ) ; ijarg = ijarg + 1
+     CASE ( '-vm') ; CALL getarg(ijarg, cv_pool    ) ; ijarg = ijarg + 1
+     CASE ('-nc4') ; lnc4=.TRUE.
+     CASE DEFAULT
+        PRINT *, ' Option ', TRIM(cdum),' not understood'
+        STOP
+     END SELECT
+  ENDDO
+
+  lchk = lchk .OR. chkfile (cf_fill   )
+  lchk = lchk .OR. chkfile (cf_isflist)
+  lchk = lchk .OR. chkfile (cf_pat    )
+  lchk = lchk .OR. chkfile (cf_pool   )
+  lchk = lchk .OR. chkfile (cn_fzgr   )
+  lchk = lchk .OR. chkfile (cn_fhgr   )
+  IF ( lchk  ) STOP ! missing file
+
+  npiglo = getdim (cf_fill, cn_x)
+  npjglo = getdim (cf_fill, cn_y)
+  npk    = 0  ! working with 2D files only
+
+  PRINT *, 'NPIGLO = ', npiglo
+  PRINT *, 'NPJGLO = ', npjglo
+  PRINT *, 'NPK    = ', npk
+
+  ALLOCATE(de12t(npiglo,npjglo))
+  ALLOCATE(ipoolmsk(npiglo, npjglo), dfwfisf2d(npiglo, npjglo)    )
+  ALLOCATE(dl_fwfisf2d(npiglo,npjglo), dl_fwfispat(npiglo,npjglo))
+  ALLOCATE(isfindex(npiglo, npjglo), isfindex_wk(npiglo, npjglo) )
+
+  ALLOCATE (stypvar(1))
+  ALLOCATE (ipk(1),id_varout(1))
+  ! initialisation of final fwf
+  dfwfisf2d(:,:) = 0.0d0
+
+  CALL CreateOutput
+
+  ! define variable
+  ! read ice shelf draft data
+  de12t(:,:)    = getvar(cn_fhgr, cn_ve1t,  1, npiglo, npjglo ) *  getvar(cn_fhgr, cn_ve2t,  1, npiglo, npjglo )
+
+  ! open isf file
+  OPEN(unit=iunit, file=cf_isflist, form='formatted', status='old')
+  ! get number of isf
+  nisf = 0
+  cdum='XXX'
+  DO WHILE ( TRIM(cdum) /= 'EOF')
+     READ(iunit,*) cdum
+     nisf=nisf+1
+  END DO
+  REWIND(iunit)
+  nisf = nisf - 1
+
+  PRINT *, '   Number of ISF found in file list : ', nisf
+
+  ! Read the Basal melting pattern, once for all
+  dl_fwfispat(:,:) = getvar(cf_pat , cv_pat, 1 ,npiglo, npjglo )
+  isfindex(:,:)    = getvar(cf_fill, cv_fill,1 ,npiglo, npjglo )  
+  ipoolmsk(:,:)    = getvar(cf_pool, cv_pool,1 ,npiglo, npjglo )
+
+  ! loop over all the ice shelf
+  DO jisf=1,nisf
+     ! initialize working pattern with the fixed one
+     dl_fwfisf2d = dl_fwfispat
+
+     ! reset working isf index to its initial value
+     isfindex_wk(:,:) = isfindex(:,:)
+
+     ! eliminate closed pools from isfindex, using ISF-pool file
+     isfindex_wk = isfindex_wk * ipoolmsk
+
+     ! read ice shelf data
+     READ(iunit,*) ifill,cdum,rlon, rlat, iiseed, ijseed ,rdraftmin, rdraftmax, dfwf
+
+     ! convertion of total ice shelf melting from Gt/y -> kg/s
+     dl_fwf = dfwf * 1.d9 * 1.d3 / 86400.d0 / 365.d0
+
+     ! initialisation of cumulative variable
+     dsumcoef = 0.0d0
+
+     ! isolate the ice shelf data we want
+     WHERE (isfindex_wk /= -ifill)
+        isfindex_wk(:,:) = 0      ! eliminate all ISF not current (-ifill)
+        dl_fwfisf2d(:,:) = 0.0d0
+     END WHERE
+
+     ! set the halo to 0 (to avoid double counting)  ( E-W periodicity !)
+     dl_fwfisf2d(1,:)=0.0d0 ; dl_fwfisf2d(npiglo,:)=0.0d0 ;
+
+     dsumcoef = SUM(dl_fwfisf2d * de12t)
+     dl_fwfisf2d(:,:) = dl_fwfisf2d(:,:) / dsumcoef * dl_fwf
+
+     ! Value read from the text file has the wrong sign for melting.
+     ! As the shelves are disjoint, cumulate is OK !
+     dfwfisf2d(:,:) = dfwfisf2d(:,:) - dl_fwfisf2d(:,:)
+  END DO
+
+  ! print isf forcing file
+  ierr = putvar(ncout, id_varout(1), dfwfisf2d, 1, npiglo, npjglo)
+
+  ! close file
+  ierr = closeout(ncout)
+
+CONTAINS
+  SUBROUTINE CreateOutput
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE CreateOutput  ***
+    !!
+    !! ** Purpose :  Create the output file. This is done outside the main
+    !!               in order to increase readability of the code. 
+    !!
+    !! ** Method  :  Use global variables, defined in mail 
+    !!----------------------------------------------------------------------
+    ! define new variables for output
+    stypvar(1)%ichunk            = (/npiglo,MAX(1,npjglo/30),1,1 /)
+    stypvar(1)%cname             = 'sofwfisf'
+    stypvar(1)%cunits            = 'kg/s'
+    stypvar(1)%rmissing_value    =  -99.d0
+    stypvar(1)%valid_min         =  0.d0
+    stypvar(1)%valid_max         =  2000.d0
+    stypvar(1)%clong_name        = 'Ice Shelf Fresh Water Flux '
+    stypvar(1)%cshort_name       = 'sofwfisf'
+    stypvar(1)%conline_operation = 'N/A'
+    stypvar(1)%caxis             = 'TYX'
+    stypvar(1)%cprecision        = 'r8'
+    ipk(1) = 1  !  2D
+
+    ! create output file taking the sizes in cf_fill
+    ncout  = create      (cf_out, cf_fill, npiglo, npjglo, npk,   ld_nc4=lnc4 )
+    ierr   = createvar   (ncout , stypvar, 1,  ipk,  id_varout,   ld_nc4=lnc4 )
+    ierr   = putheadervar(ncout,  cn_fzgr, npiglo, npjglo, npk                )
+
+  END SUBROUTINE CreateOutput
+
+END PROGRAM cdfisf_forcing
diff --git a/src/cdfisf_poolchk.f90 b/src/cdfisf_poolchk.f90
new file mode 100644
index 0000000..13bb20b
--- /dev/null
+++ b/src/cdfisf_poolchk.f90
@@ -0,0 +1,213 @@
+PROGRAM cdfisf_poolchk
+  !!======================================================================
+  !!                     ***  PROGRAM  cdfisf_poolchk  ***
+  !!=====================================================================
+  !!  ** Purpose : Build a mask-like file that marks the un-connected point
+  !!              in a 3D mask files. Un-connected points are points which
+  !!              do not communicate with the open ocean. This case is
+  !!              frequent for the ocean cavity below the ice shelves.
+  !!
+  !!  ** Method  : Use a fillpool3D algorithm. This program use 3D arrays
+  !!               and may be very memory consuming for big domains.
+  !!
+  !! History :   3.0  : 11/2016  : J.M. Molines. P. Mathiot (original code)
+  !!----------------------------------------------------------------------
+  !!   routines                                         : description
+  !!----------------------------------------------------------------------
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE modcdfnames
+  USE modutils
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2012
+  !! $Id$
+  !! Copyright (c) 2012, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4) :: ji, jj, jk
+  INTEGER(KIND=4) :: ierr, ncout
+  INTEGER(KIND=4) :: npiglo, npjglo, npk
+  INTEGER(KIND=4) :: iiseed, ijseed, ikseed, ijmax
+  INTEGER(KIND=4) :: ifill = 2
+  INTEGER(KIND=4) :: narg, ijarg
+  INTEGER(KIND=4) :: ncid, id
+  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: ipk                ! arrays of vertical level for each var
+  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_varout          ! varid's of average vars
+
+  INTEGER(KIND=2), DIMENSION(:,:),   ALLOCATABLE :: itab
+  INTEGER(KIND=2), DIMENSION(:,:,:), ALLOCATABLE :: itab3d, itmask
+
+  REAL(KIND=4), DIMENSION(:),        ALLOCATABLE :: rsum              ! iceshelf draft
+  REAL(KIND=4), DIMENSION(:,:),      ALLOCATABLE :: rdraft            ! iceshelf draft
+
+  CHARACTER(LEN=255) :: cf_in
+  CHARACTER(LEN=255) :: cf_out='poolmask.nc'
+  CHARACTER(LEN=255) :: cf_isfdr='isf_draft.nc'
+  CHARACTER(LEN=255) :: cv_isfdr='isf_draft'
+  CHARACTER(LEN=255) :: cdum
+
+  TYPE (variable), DIMENSION(:),    ALLOCATABLE :: stypvar            ! attributes for average values
+
+  LOGICAL            :: lchk=.FALSE.
+  LOGICAL            :: lnc4=.FALSE.
+  !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+  ! input file is a mask file, then :
+  cn_t='t'
+  cn_z='z'
+  cn_vdeptht='nav_lev'
+
+  narg = iargc()
+
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage : cdfisf_poolchk -m MASK-file -d ISFDRAFT-file [-v ISFDRAFT-variable]'
+     PRINT *,'            [-nc4] [-o OUT-file]'
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'       Produce a netcdf mask file with 1 everywhere, except for points '
+     PRINT *,'       not connected to the open ocean (Frequent for cavities below '
+     PRINT *,'       ice-shelves), which have 0 value. Both 3D and 2D variables are'
+     PRINT *,'       created, the 2D variables beiing used for cdfisf_forcing.'
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       -m MASK-file : name of the input NEMO mask file, with tmask variable.'
+     PRINT *,'       -d ISFDRAFT-file : name of the file with ice shelf draft.'
+     PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'       -v ISFDRAFT-variable: name of the variable for ice shelf draft.'
+     PRINT *,'       -nc4 : use netcdf4 with chunking and deflation for the output.'
+     PRINT *,'       -o OUT-file : name of the output file. [Default : ',TRIM(cf_out),' ]' 
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'       Only the mask file given as argument' 
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file : ', TRIM(cf_out),' unless -o option is used.'
+     PRINT *,'         variables : tmask_pool3d, tmask_pool2d'
+     PRINT *,'      '
+     PRINT *,'     SEE ALSO :'
+     PRINT *,'      cdfisf_fill, cdfisf_forcing, cdfisf_rnf' 
+     PRINT *,'      '
+     STOP
+  ENDIF
+  
+  ijarg=1
+  DO WHILE ( ijarg <= narg )
+     CALL getarg(ijarg, cdum) ; ijarg = ijarg+1
+     SELECT CASE ( cdum )
+     CASE ( '-m'  ) ; CALL getarg(ijarg, cf_in   ) ; ijarg = ijarg+1
+     CASE ( '-o'  ) ; CALL getarg(ijarg, cf_out  ) ; ijarg = ijarg+1
+     CASE ( '-d'  ) ; CALL getarg(ijarg, cf_isfdr) ; ijarg = ijarg+1
+     CASE ( '-v'  ) ; CALL getarg(ijarg, cv_isfdr) ; ijarg = ijarg+1
+     CASE ( '-nc4') ; lnc4=.TRUE.
+     CASE DEFAULT 
+        PRINT *,' Unknown option : ', TRIM(cdum)
+        STOP
+     END SELECT
+  ENDDO
+
+  lchk = lchk .OR. chkfile(cf_in    )
+  lchk = lchk .OR. chkfile(cf_isfdr)
+  IF ( lchk ) STOP ! missing files
+
+  npiglo = getdim (cf_in,cn_x )
+  npjglo = getdim (cf_in,cn_y )
+  npk    = getdim (cf_in,cn_z )
+
+  PRINT *, ' NPIGLO = ', npiglo
+  PRINT *, ' NPJGLO = ', npjglo
+  PRINT *, ' NPK    = ', npk
+
+  ALLOCATE ( itab(npiglo, npjglo), itab3d( npiglo, npjglo, npk), itmask(npiglo, npjglo,npk) )
+  ALLOCATE ( rdraft(npiglo, npjglo), rsum(npjglo) )
+  ALLOCATE ( ipk(2), id_varout(2), stypvar(2))
+
+  CALL CreateOutput
+
+  ! Read ice shelf draft in order to find the northern limit of the cavities
+  rdraft(:,:) = getvar(cf_isfdr, cv_isfdr, 1, npiglo, npjglo )
+  rsum(:)     = SUM(rdraft, DIM=1 )
+  ijmax=2
+  DO jj=1, npjglo-1
+     IF ( rsum(jj) /= 0. ) THEN
+       ijmax=jj
+     ENDIF
+  ENDDO
+  ijmax = MIN ( npjglo, ijmax+10 )
+
+  ! JMM :note the use of 3D array ( very unusual in CDFTOOLS )
+  itmask(:,:,:) = getvar3d (cf_in, cn_tmask, npiglo, npjglo, npk)
+  itab3d(:,:,:) = itmask(:,:,:)
+
+  ! set limits  for fillpool algo
+  itab3d(:,ijmax  ,1:npk-1) = 0
+  itab3d(:,ijmax-1,:) = 1  ! open a connection for sure at ijmax -1 (out of iceshelf cavities)
+  itab3d(:,:,    1)   = 0  ! to set an upper limit !, assuming to cavities at this level
+  iiseed= npiglo/2  ; ijseed = ijmax -1 ; ikseed = 2
+  PRINT *,' SEED position',iiseed, ijseed, ikseed, itab3d(iiseed, ijseed, ikseed)
+
+  CALL FillPool3D( iiseed, ijseed,ikseed, itab3d, -ifill )
+  PRINT *, '  Number of disconected points : ', COUNT(  (itab3d(:,1:ijmax-2,:) == 1) )
+  ! at this point itab3d (:,1:ijmax,:) can have 3 different values :
+  !              0 where there where already 0
+  !              -ifill where the ocean points are connected
+  !              1 where ocean points in tmask are not connected
+  itab(:,:) = itmask(:,:,1)  ! restore original tmask at surface
+  itab(:,1:ijmax-2) = SUM(itab3d(:,1:ijmax-2,:), dim=3) 
+  WHERE (itab(:,1:ijmax-2) > 0 ) itab(:,1:ijmax-2)=0
+  WHERE (itab(:,1:ijmax-2) < 0 ) itab(:,1:ijmax-2)=1
+  
+  ierr = putvar( ncout, id_varout(1), itab(:,:), 1, npiglo, npjglo)
+
+  DO jk = 1, npk 
+    ierr = putvar( ncout, id_varout(2), itab3d(:,:,jk), jk, npiglo, npjglo)
+  ENDDO
+
+  ierr = closeout(ncout)
+
+CONTAINS
+  SUBROUTINE CreateOutput
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE CreateOutput  ***
+    !!
+    !! ** Purpose :  Create the output file. This is done outside the main
+    !!               in order to increase readability of the code. 
+    !!
+    !! ** Method  :  Use global variables, defined in mail 
+    !!----------------------------------------------------------------------
+  ! define new variables for output
+  stypvar(1)%ichunk            = (/npiglo,MAX(1,npjglo/30),1,1 /)
+  stypvar(1)%cname             = 'tmask_pool2d'
+  stypvar(1)%rmissing_value    =  -99.
+  stypvar(1)%valid_min         =  0.
+  stypvar(1)%valid_max         =  1.
+  stypvar(1)%clong_name        = '2d isf pool mask'
+  stypvar(1)%cshort_name       = 'tmask_pool2d'
+  stypvar(1)%conline_operation = 'N/A'
+  stypvar(1)%caxis             = 'TYX'
+  stypvar(1)%cprecision        = 'by'
+  ipk(1) = 1  !  2D
+  ! define new variables for output
+  stypvar(2)%ichunk            = (/npiglo,MAX(1,npjglo/30),1,1 /)
+  stypvar(2)%cname             = 'tmask_pool3d'
+  stypvar(2)%rmissing_value    =  -99.
+  stypvar(2)%valid_min         =  0.
+  stypvar(2)%valid_max         =  1
+  stypvar(2)%clong_name        = '3d isf pool mask'
+  stypvar(2)%cshort_name       = 'tmask_pool3d'
+  stypvar(2)%conline_operation = 'N/A'
+  stypvar(2)%caxis             = 'TZYX'
+  stypvar(2)%cprecision        = 'by'
+  ipk(2) = npk  !  3D
+
+  ! create output file taking the sizes in cf_fill
+  ncout  = create      (cf_out, cf_in,   npiglo, npjglo, npk, cdepvar=cn_vdeptht, ld_nc4=lnc4)
+  ierr   = createvar   (ncout,  stypvar, 2,   ipk, id_varout,                     ld_nc4=lnc4)
+  ierr   = putheadervar(ncout,  cf_in,   npiglo, npjglo, npk              )
+
+
+  END SUBROUTINE CreateOutput
+
+END PROGRAM cdfisf_poolchk
diff --git a/src/cdfisf_rnf.f90 b/src/cdfisf_rnf.f90
new file mode 100644
index 0000000..f2a1c7e
--- /dev/null
+++ b/src/cdfisf_rnf.f90
@@ -0,0 +1,316 @@
+PROGRAM cdfisf_rnf
+  !!======================================================================
+  !!                     ***  PROGRAM  cdfisf_rnf  ***
+  !!=====================================================================
+  !!  ** Purpose : Prepare netcdf file with Ice Shelf melting parametrized
+  !!               as runoff (spread on the vertical)
+  !!
+  !!  ** Method  : 
+  !!
+  !! History : 3.0  : 04/2014  : P.Mathiot 
+  !!----------------------------------------------------------------------
+  !!----------------------------------------------------------------------
+  USE cdfio 
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2016
+  !! $Id: cdfisf_rnf.f90 668 2013-05-30 12:54:00Z molines $
+  !! Copyright (c) 2016, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!-----------------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)                               :: jisf, ji, jj, jw   ! dummy loop index
+  INTEGER(KIND=4)                               :: ierr               ! working integer
+  INTEGER(KIND=4)                               :: narg, iargc, ijarg ! browsing command line
+  INTEGER(KIND=4)                               :: npiglo, npjglo, npk! size of the domain
+  INTEGER(KIND=4)                               :: nisf, nwidth       ! number of ice shelves
+  INTEGER(KIND=4)                               :: iunit=10           ! id file
+  INTEGER(KIND=4)                               :: ncout              ! ncid of output files
+  INTEGER(KIND=4)                               :: ifill
+  INTEGER(KIND=4)                               :: iiseed, ijseed     ! position of a point within ice shelf
+  INTEGER(KIND=4)                               :: ijmin, ijmax       ! j-limits of a particular ice shelf
+  INTEGER(KIND=4)                               :: iwscale=75         ! horizontal scale of the fading function (points)
+  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: ipk                ! arrays of vertical level for each var
+  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_varout          ! varid's of average vars
+  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: isum               ! zonal sum of isf index for optim
+  INTEGER(KIND=2), DIMENSION(:,:),  ALLOCATABLE :: isfindex, isfmask  ! 
+  INTEGER(KIND=2), DIMENSION(:,:),  ALLOCATABLE :: isfindex_wk        !
+
+  REAL(KIND=4)                                  :: rdraftmax, rdraftmin ! dummy information in input file
+  REAL(KIND=4)                                  :: rlon, rlat         ! dummy information in input file
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: bathy, zdrft       ! bathymetry and ice shelf draft
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: zmax2d, zmin2d     ! output arrays
+
+  REAL(KIND=8)                                  :: dfwf
+  REAL(KIND=8)                                  :: dl_fwf, dsumcoef
+  REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: de12t
+  REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: dl_fwfisf2d
+  REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: dfwfisf2d
+
+  !                                                FILES
+  CHARACTER(LEN=256)                            :: cf_fill            ! input file names
+  CHARACTER(LEN=256)                            :: cf_isflist         ! input file names
+  CHARACTER(LEN=256)                            :: cf_bathy='bathy.nc'! bathymetry file name
+  CHARACTER(LEN=256)                            :: cf_isfdr='isf_draft.nc'! ice_draft file name
+  CHARACTER(LEN=256)                            :: cf_out='rnfisf.nc' ! output file for average
+  !                                                VARIABLES
+  CHARACTER(LEN=256)                            :: cv_fill            ! fill var name
+  CHARACTER(LEN=256)                            :: cv_bathy='Bathymetry' ! bathymetry name
+  CHARACTER(LEN=256)                            :: cv_isfdr='isf_draft'  ! ice shelf draft name
+  CHARACTER(LEN=256)                            :: cdum               ! dummy string argument
+  
+  TYPE (variable), DIMENSION(:),    ALLOCATABLE :: stypvar            ! attributes for average values
+
+  LOGICAL                                       :: lchk    = .false.  ! flag for missing files
+  LOGICAL                                       :: lnc4    = .false.  ! flag for netcdf4 chunking and deflation
+  !!----------------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  narg= iargc()
+
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage : cdfisf_rnf -f ISF-fill-file -v ISF-fill_var -l ISF-listfile -w width '
+     PRINT *,'     [-b BATHY-file] [-vb BATHY-var] [-i ISFDRAFT-file] [-vi ISFDRAFT-variable]'
+     PRINT *,'     [-nc4] [-o OUT-file ]'
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'        Build a netcdf file runoff file using the basal melting of the '
+     PRINT *,'        ice-shelves. This netcdf file is intented to be used with NEMO when'
+     PRINT *,'        nn_isf namelist parameter is set to 3.'
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'          -f ISF-fill_file : file built by cdffill (all the ice shelves are'
+     PRINT *,'                             tagged with an id)'
+     PRINT *,'          -v ISF-fill_var  : name of fill variable to use in ISF-fill_file'
+     PRINT *,'          -l ISF-list : Text file with the melting rate (GT/y) given for'
+     PRINT *,'               each ice shelf.' 
+     PRINT *,'          -w width : specify the width (in grid points) on which the run-off'
+     PRINT *,'               will be applied.'
+     PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'          -b BATHY-file : give name of bathy file.'
+     PRINT *,'                      [ default : ',TRIM(cf_bathy),' ]'
+     PRINT *,'          -vp BATHY-var : give name of bathy variable.'
+     PRINT *,'                      [ default : ',TRIM(cv_bathy),' ]'
+     PRINT *,'          -i ISFDRAFT-file : give name of isf_draft file.'
+     PRINT *,'                      [ default : ',TRIM(cf_isfdr),' ]'
+     PRINT *,'          -vi ISFDRAFT-var : give name of isf_draft variable.'
+     PRINT *,'                      [ default : ',TRIM(cv_isfdr),' ]'
+     PRINT *,'          -nc4 : Use this option to have netcdf4 output file, with chunking'
+     PRINT *,'               and deflation.'
+     PRINT *,'          -o OUT-file : Specify the name of the output file instead of '
+     PRINT *,'               the default name ',TRIM(cf_out)
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'       mesh_hgr.nc and all files specified on the command line' 
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file : ', TRIM(cf_out) ,' unless -o option used'
+     PRINT *,'         variables : sozisfmax (m), sozisfmin(m), sofwfisf (kg/m2/s)'
+     PRINT *,'      '
+     PRINT *,'     SEE ALSO :'
+     PRINT *,'       cdfisf_fill, cdfisf_forcing, cdfisf_poolchk'
+     PRINT *,'      '
+     STOP
+  ENDIF
+
+  ijarg=1
+  DO WHILE ( ijarg <= narg )
+    CALL getarg(ijarg,cdum) ; ijarg=ijarg+1
+    SELECT CASE (cdum)
+    CASE ('-f' ) ; CALL getarg(ijarg,cf_fill   ) ; ijarg=ijarg+1
+    CASE ('-v' ) ; CALL getarg(ijarg,cv_fill   ) ; ijarg=ijarg+1
+    CASE ('-l' ) ; CALL getarg(ijarg,cf_isflist) ; ijarg=ijarg+1
+    CASE ('-w' ) ; CALL getarg(ijarg,cdum      ) ; ijarg=ijarg+1
+                   READ(cdum,*) nwidth
+    CASE ('-b' ) ; CALL getarg(ijarg,cf_bathy  ) ; ijarg=ijarg+1
+    CASE ('-vb') ; CALL getarg(ijarg,cv_bathy  ) ; ijarg=ijarg+1
+    CASE ('-i' ) ; CALL getarg(ijarg,cf_isfdr  ) ; ijarg=ijarg+1
+    CASE ('-vi') ; CALL getarg(ijarg,cv_isfdr  ) ; ijarg=ijarg+1
+
+    CASE ('-nc4'); lnc4 = .TRUE.
+    CASE ('-o' ) ; CALL getarg(ijarg,cf_out    ) ; ijarg=ijarg+1
+    CASE DEFAULT 
+        PRINT *,' Option ',TRIM(cdum),' not understood'
+        STOP
+    END SELECT
+  ENDDO
+
+  lchk = lchk .OR. chkfile (cf_fill   )
+  lchk = lchk .OR. chkfile (cf_isflist)
+  lchk = lchk .OR. chkfile (cf_bathy  )
+  lchk = lchk .OR. chkfile (cf_isfdr  )
+  lchk = lchk .OR. chkfile (cn_fhgr   )
+
+  IF ( lchk ) STOP ! missing file
+
+  npiglo = getdim (cf_fill, cn_x)
+  npjglo = getdim (cf_fill, cn_y)
+  npk    = 0                  ! bathy file has no dep dimension
+
+  PRINT *, 'NPIGLO = ', npiglo
+  PRINT *, 'NPJGLO = ', npjglo
+  PRINT *, 'NPK    = ', npk
+
+  ALLOCATE(isfindex (npiglo, npjglo), isfmask    (npiglo, npjglo))
+  ALLOCATE(isfindex_wk(npiglo, npjglo), isum(npjglo))
+
+  ALLOCATE(bathy    (npiglo, npjglo), zdrft      (npiglo, npjglo))
+  ALLOCATE(zmax2d   (npiglo, npjglo), zmin2d     (npiglo, npjglo))
+
+  ALLOCATE(de12t    (npiglo, npjglo) )
+  ALLOCATE(dfwfisf2d(npiglo, npjglo), dl_fwfisf2d(npiglo, npjglo))
+
+  ALLOCATE (stypvar(3))
+  ALLOCATE (ipk(3),id_varout(3))
+
+  CALL CreateOutput
+  
+  ! define variable
+  ! read ice shelf draft data
+  isfindex(:,:) = getvar(cf_fill,  cv_fill,  1 ,npiglo, npjglo )  ! fill index
+  bathy(:,:)    = getvar(cf_bathy, cv_bathy, 1, npiglo, npjglo )  ! ocean bathy
+  zdrft(:,:)    = getvar(cf_isfdr, cv_isfdr, 1, npiglo, npjglo )  ! ice shelf draft
+  de12t(:,:)    = getvar(cn_fhgr,  cn_ve1t,  1, npiglo, npjglo ) * getvar(cn_fhgr, cn_ve2t, 1, npiglo, npjglo )
+
+  ! open isf file
+  OPEN(unit=iunit, file=cf_isflist, form='formatted', status='old')
+  ! get number of isf
+  nisf = 0
+  cdum='XXX'
+  DO WHILE ( TRIM(cdum) /= 'EOF')
+     READ(iunit,*) cdum
+     nisf=nisf+1
+  END DO
+  REWIND(iunit)
+  nisf = nisf - 1
+
+  PRINT *, '   Number of ISF found in file list : ', nisf
+
+  DO jisf=1,nisf
+     ! reset working isf index to its initial value
+     isfindex_wk(:,:) = isfindex(:,:)
+
+     ! read ice shelf data for jsf
+     READ(iunit,*) ifill,cdum,rlon, rlat, iiseed, ijseed ,rdraftmin, rdraftmax, dfwf
+
+     dl_fwf = dfwf * 1.d9 * 1.d3 / 86400.d0 / 365.d0  ! convert GT/yr to kg/m2/s
+     isfmask    (:,:) = 0
+     dl_fwfisf2d(:,:) = 0.0d0
+     dsumcoef         = 0.0d0
+     zmax2d(:,:)      = rdraftmax
+     zmin2d(:,:)      = rdraftmin
+
+     ! only deal with current ice shelf
+     WHERE (isfindex_wk /=  -ifill ) isfindex_wk = 0
+
+     ! find the j-limits for the current ice shelf 
+     isum(:)=SUM(isfindex_wk,dim=1)
+     ijmin = npjglo ; ijmax=2
+     DO jj=ijseed, 2, -1
+        IF ( isum(jj) /= 0 ) THEN
+          ijmin=jj
+        ENDIF
+     ENDDO
+     DO jj=ijseed, npjglo-1
+        IF ( isum(jj) /= 0 ) THEN
+          ijmax=jj
+        ENDIF
+     ENDDO
+
+     DO jw = 1,nwidth
+        DO ji=2,npiglo-1
+           DO jj = ijmin, ijmax
+              IF ( zdrft(ji,jj) == 0 .AND.  &    ! not under ice_shelf
+              &    bathy(ji,jj) /= 0 .AND.  &    ! but in the ocean
+              &    MINVAL(isfindex_wk(ji-1:ji+1 , jj-1:jj+1)) == -ifill  .AND. &  ! 
+              &    isfindex_wk(ji,jj) == 0 ) THEN
+                 ! compute dfwf in mm/s  ???
+                 isfmask(ji,jj)  = isfmask(ji,jj) + jw 
+                 ! use an empirical ocean ward fading function, in order to distribute the
+                 ! runoff on nwidth points along the coast. iwscale can be adapted for
+                 ! sharper (decrease) or flatter (increase) fading function. Default = 75
+                 dl_fwfisf2d(ji,jj) = exp(-((isfmask(ji,jj)-1.)/iwscale)**2)  
+              END IF
+           END DO
+        END DO
+        WHERE (isfmask >= 1) isfindex_wk = -ifill ! capture already treated points under the shelf
+     END DO
+
+     dsumcoef=SUM(dl_fwfisf2d)
+     PRINT *, SUM(dl_fwfisf2d), dsumcoef, SUM(dl_fwfisf2d / dsumcoef), dl_fwf, dfwf
+     WHERE (isfmask >= 1)
+       dl_fwfisf2d = dl_fwfisf2d / dsumcoef * dl_fwf / de12t
+     END WHERE
+     dfwfisf2d = dfwfisf2d + dl_fwfisf2d
+  END DO
+  ierr = putvar(ncout, id_varout(1), zmax2d   , 1, npiglo, npjglo)
+  ierr = putvar(ncout, id_varout(2), zmin2d   , 1, npiglo, npjglo)
+  ierr = putvar(ncout, id_varout(3), dfwfisf2d, 1, npiglo, npjglo)
+
+  ierr = closeout(ncout)
+
+  ! Diagnose total amount of fwf
+  dl_fwf = 0.0d0
+  DO ji=2,npiglo-1
+     DO jj=2,npjglo-1
+        dl_fwf = dl_fwf + dfwfisf2d(ji,jj) * de12t(ji,jj) * 86400.d0 * 365.d0
+     END DO
+  END DO
+  PRINT *, 'total sum of isf = ', dl_fwf
+
+CONTAINS
+
+  SUBROUTINE CreateOutput 
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE CreateOutput  ***
+    !!
+    !! ** Purpose :  Create output netcdf output file using cdfio 
+    !!              We use a routine just to increase readability
+    !! ** Method  :  Use global variables to know about the file to be created
+    !!           
+    !!----------------------------------------------------------------------
+  ! define new variables for output
+  stypvar(1)%ichunk            = (/npiglo,MAX(1,npjglo/30),1,1 /)
+  stypvar(1)%cname             = 'sozisfmax'
+  stypvar(1)%rmissing_value    =  -99.
+  stypvar(1)%valid_min         =  0.
+  stypvar(1)%valid_max         =  2000.
+  stypvar(1)%clong_name        = 'max depth of isf'
+  stypvar(1)%cshort_name       = 'sozisfmax'
+  stypvar(1)%conline_operation = 'N/A'
+  stypvar(1)%caxis             = 'TYX'
+  ipk(1) = 1  !  2D
+  ! define new variables for output
+  stypvar(2)%ichunk            = (/npiglo,MAX(1,npjglo/30),1,1 /)
+  stypvar(2)%cname             = 'sozisfmin'
+  stypvar(2)%rmissing_value    =  -99.
+  stypvar(2)%valid_min         =  0.
+  stypvar(2)%valid_max         =  2000.
+  stypvar(2)%clong_name        = 'min depth of isf'
+  stypvar(2)%cshort_name       = 'sozisfmin'
+  stypvar(2)%conline_operation = 'N/A'
+  stypvar(2)%caxis             = 'TYX'
+  ipk(2) = 1  !  2D
+  ! define new variables for output
+  stypvar(3)%ichunk            = (/npiglo,MAX(1,npjglo/30),1,1 /)
+  stypvar(3)%cname             = 'sofwfisf'
+  stypvar(3)%rmissing_value    =  -99.d0
+  stypvar(3)%valid_min         =  0.
+  stypvar(3)%valid_max         =  2000.
+  stypvar(3)%clong_name        = 'fwfisf'
+  stypvar(3)%cshort_name       = 'sofwfisf'
+  stypvar(3)%conline_operation = 'N/A'
+  stypvar(3)%caxis             = 'TYX'
+  stypvar(3)%cprecision        = 'r8'
+  ipk(3) = 1  !  2D
+
+  ! create output file taking the sizes in cf_fill
+  ncout  = create      (cf_out, cf_fill,   npiglo, npjglo, npk,  ld_nc4=lnc4)
+  ierr   = createvar   (ncout,  stypvar, 3,   ipk, id_varout  ,  ld_nc4=lnc4)
+  ierr   = putheadervar(ncout,  cf_fill,   npiglo, npjglo, npk              )
+
+  END SUBROUTINE CreateOutput
+
+END PROGRAM cdfisf_rnf
diff --git a/cdfisopsi.f90 b/src/cdfisopsi.f90
similarity index 100%
rename from cdfisopsi.f90
rename to src/cdfisopsi.f90
diff --git a/cdfkempemekeepe.f90 b/src/cdfkempemekeepe.f90
similarity index 100%
rename from cdfkempemekeepe.f90
rename to src/cdfkempemekeepe.f90
diff --git a/src/cdflap.f90 b/src/cdflap.f90
new file mode 100644
index 0000000..67286d6
--- /dev/null
+++ b/src/cdflap.f90
@@ -0,0 +1,322 @@
+PROGRAM cdflap
+  !!======================================================================
+  !!                     ***  PROGRAM  cdflap  ***
+  !!=====================================================================
+  !!  ** Purpose : Compute the laplacian of a field given in argument
+  !!
+  !!  ** Method  : Use a classical centered stencil
+  !!               Gradient along the coasline are set to 0
+  !!
+  !! History :  3.0  : 09/2014  : J.M. Molines 
+  !!          
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id$
+  !! Copyright (c) 2011, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)                              :: ji, jj, jk, jt, jv ! dummy loop index
+  INTEGER(KIND=4)                              :: npiglo, npjglo     ! size of the domain
+  INTEGER(KIND=4)                              :: npk, npt           ! size of the domain
+  INTEGER(KIND=4)                              :: npkv               ! vertical size of the variable
+  INTEGER(KIND=4)                              :: narg, iargc, ijarg ! browse line
+  INTEGER(KIND=4)                              :: ii                 ! browse line
+  INTEGER(KIND=4)                              :: ncout              ! ncid of output file
+  INTEGER(KIND=4)                              :: nvars              ! nmber of variables in input file
+  INTEGER(KIND=4)                              :: ierr               ! error status
+  INTEGER(KIND=4)                              :: iioff1, iioff2     ! i-offset for mask
+  INTEGER(KIND=4)                              :: ijoff1, ijoff2     ! j-offset for mask
+  INTEGER(KIND=4)                              :: ii1, ii2, ij1, ij2 ! working index
+  INTEGER(KIND=4), DIMENSION(1)                :: ipk, id_varout     ! levels and varid's of output vars
+  INTEGER(KIND=4), DIMENSION(:),   ALLOCATABLE :: ipkin              ! ipk of all variables in input files
+
+  REAL(KIND=4), DIMENSION(:,:),    ALLOCATABLE :: e1_i1, e1_i2       ! along i horizontal metric
+  REAL(KIND=4), DIMENSION(:,:),    ALLOCATABLE :: e2_j1, e2_j2       ! along j horizontal metric
+  REAL(KIND=4), DIMENSION(:,:),    ALLOCATABLE :: rmski, rmskj       ! relevant mask
+  REAL(KIND=4), DIMENSION(:,:),    ALLOCATABLE :: v2d                ! input variable
+  REAL(KIND=4), DIMENSION(:,:),    ALLOCATABLE :: ff                 ! Coriolis
+  REAL(KIND=4), DIMENSION(:,:),    ALLOCATABLE :: gphi               ! Coriolis
+  REAL(KIND=4), DIMENSION(:),      ALLOCATABLE :: tim                ! time counter
+  REAL(KIND=4)                                 :: rmissing           ! missing value or_FillValue of input variable
+  REAL(KIND=4)                                 :: grav=9.81          ! Gravity acceleration (m2/s)
+  REAL(KIND=4)                                 :: omega              ! earth rotation rate
+  REAL(KIND=4)                                 :: rpi                ! 3.14159...
+
+  REAL(KIND=8), DIMENSION(:,:),    ALLOCATABLE :: dlap               ! output laplacian
+  REAL(KIND=8)                                 :: dspval=99999.d0    ! output laplacian
+
+  CHARACTER(LEN=256)                           :: cf_in              ! input file name
+  CHARACTER(LEN=256)                           :: cv_in              ! input variable name
+  CHARACTER(LEN=256)                           :: cv_units           ! units of input variable name
+  CHARACTER(LEN=256)                           :: cv_lat             ! name of latitude variable in hgr
+  CHARACTER(LEN=3)                             :: ct_in              ! input variable type [ T U V F ] on C-grid
+  CHARACTER(LEN=256)                           :: cf_out='lap.nc'    !output file name
+  CHARACTER(LEN=256)                           :: cln_in             ! Long name of input variable
+  CHARACTER(LEN=256)                           :: csn_in             ! Short name of input variable
+  CHARACTER(LEN=256)                           :: cldum              ! dummy string
+  CHARACTER(LEN=10)                            :: ce1_i1, ce1_i2     ! name of relevant horizontal i-metric
+  CHARACTER(LEN=10)                            :: ce2_j1, ce2_j2     ! name of relevant horizontal i-metric
+  CHARACTER(LEN=10)                            :: cmask_i, cmask_j   ! name of relevant mask variable
+  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_nam             ! array of var name
+
+  TYPE(variable), DIMENSION(1)                 :: stypvar            ! output attributes
+  TYPE(variable), DIMENSION(:), ALLOCATABLE    :: sdum               ! input attributes
+
+  LOGICAL                                      :: lchk               ! missing files flag
+  LOGICAL                                      :: l_overf2=.FALSE.   ! overf flag
+  LOGICAL                                      :: l_metric=.TRUE.    ! overf flag
+  !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  narg = iargc()
+  IF ( narg < 2 ) THEN
+     PRINT *,' usage : cdflap IN-file IN-var  IN-type [-overf2] [-nometric]'
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'       Compute the Laplacian of the variable IN-var in file IN-file'
+     PRINT *,'       Assumes that the data are on a C-grid model (as NEMO) '
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       IN-file : netcdf file in input'
+     PRINT *,'       IN-var  : name of the variable to process '
+     PRINT *,'       IN-TYPE : Position of the variable on the C-grid [ T U V F ]'
+     PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'       -overf2 : save laplacien/f/f*g (where f is the local coriolis '
+     PRINT *,'            parameter, and g is the accelaration due to gravity --9.81 m/s2-- )'
+     PRINT *,'            For the SSH field, this is a proxy for geostrophic vorticity'
+     PRINT *,'       -nometric : compute laplacian without considering metrics '
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'       ',TRIM(cn_fhgr)," ",TRIM(cn_fzgr) ,' and ', TRIM(cn_fmsk)
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file : ', TRIM(cf_out) 
+     PRINT *,'         variables : lap<var> (unit/m2)'
+     PRINT *,'       if option -overf2 is used, netcdf file is lapoverf2.nc and '
+     PRINT *,'       variable is lap<var>overf2'
+    
+
+     STOP
+  ENDIF
+
+  ijarg = 1 ; ii=0
+  DO WHILE ( ijarg <= narg )
+     CALL getarg(ijarg, cldum ) ; ijarg = ijarg + 1
+     SELECT CASE (cldum )
+     CASE ( '-overf2' ) 
+          l_overf2=.true.
+          cf_out='lapoverf2.nc'
+     CASE ( '-nometric' )
+          l_metric=.false.
+          cf_out='lapgrid.nc'
+     CASE DEFAULT
+        ii=ii+1
+        SELECT CASE (ii)
+        CASE ( 1 ) ; cf_in = cldum
+        CASE ( 2 ) ; cv_in = cldum
+        CASE ( 3 ) ; ct_in = cldum
+        CASE DEFAULT
+          PRINT *,' Too many free arguments ...'
+          STOP
+        END SELECT
+     END SELECT
+  ENDDO
+  PRINT *, ' TYP ', ct_in
+
+  ! check if files exists
+  lchk=.false.
+  IF ( l_metric ) THEN
+    lchk = chkfile (cn_fhgr)
+    lchk = chkfile (cn_fzgr) .OR. lchk
+    lchk = chkfile (cn_fmsk) .OR. lchk
+  ENDIF
+  lchk = chkfile (cf_in  ) .OR. lchk
+  IF ( lchk ) STOP ! missing files
+
+  npiglo = getdim(cf_in,cn_x)
+  npjglo = getdim(cf_in,cn_y)
+  npk    = getdim(cf_in,cn_z)
+  npt    = getdim(cf_in,cn_t)
+
+ !IF ( npk == 0 ) THEN 
+ !  PRINT *, 'Input file with no vertical dimension'
+ !  PRINT *, 'Set npk to 1 '
+ !  npk = 1
+ !ENDIF
+
+  PRINT *, 'NPIGLO : ', npiglo
+  PRINT *, 'NPJGLO : ', npjglo
+  PRINT *, 'NPK    : ', npk
+  PRINT *, 'NPT    : ', npT
+  ! determine the vertical size of the working variable
+  nvars = getnvar(cf_in)   ! get the number of variables in files
+  ALLOCATE(cv_nam(nvars), ipkin(nvars) ,sdum(nvars) )
+
+  ! get list of variable names and collect attributes in stypvar
+  cv_nam(:) = getvarname(cf_in,nvars, sdum)
+  ipkin(:)  = getipk (cf_in,nvars)
+  DO jv =1, nvars
+   IF ( cv_nam(jv) == cv_in ) THEN
+     npkv=ipkin(jv)
+     EXIT
+   ENDIF
+  ENDDO
+
+  ierr = getvaratt (cf_in, cv_in, cv_units, rmissing, cln_in, csn_in)
+
+  ! define new variables for output
+  ipk(1) = npkv
+  IF ( l_overf2) THEN
+     stypvar(1)%cname             = 'lap'//TRIM(cv_in)//'overf2'
+  ELSE
+     stypvar(1)%cname             = 'lap'//TRIM(cv_in)
+  ENDIF
+  stypvar(1)%cunits            = TRIM(cv_units)//'/m2'
+  IF ( l_overf2) stypvar(1)%cunits  = TRIM(cv_units)//'/m'
+  stypvar(1)%rmissing_value    = dspval
+  stypvar(1)%valid_min         = -10.
+  stypvar(1)%valid_max         = 10.
+  stypvar(1)%clong_name        = 'Laplacian of '//TRIM(cln_in)
+  IF ( l_overf2) stypvar(1)%clong_name        = 'g /f/f* Laplacian of '//TRIM(cln_in)
+  stypvar(1)%cshort_name       = stypvar(1)%cname
+  stypvar(1)%conline_operation = 'N/A'
+  stypvar(1)%caxis             = 'TZYX'
+
+  ! fix mesh mask variables according to variable type
+  ! HOT ! need to write down stencil to fully understand those settings ...
+  SELECT CASE (ct_in )
+  CASE ( 'T' )
+      ! needs umask, vmask, e1u, e1t, e2v, e2t 
+      cmask_i = 'umask'  ; cmask_j = 'vmask'
+      ce1_i1  = cn_ve1u  ; ce1_i2  = cn_ve1t
+      ce2_j1  = cn_ve2v  ; ce2_j2  = cn_ve2t
+      iioff1  = 0        ; iioff2  = 1
+      ijoff1  = 0        ; ijoff2  = 1
+      cv_lat  =cn_gphit
+  CASE ( 'U' )
+      ! needs tmask, fmask, e1t, e1u, e2f, e2u 
+      cmask_i = 'tmask'  ; cmask_j = 'fmask'
+      ce1_i1  = cn_ve1t  ; ce1_i2  = cn_ve1u
+      ce2_j1  = cn_ve2f  ; ce2_j2  = cn_ve2u
+      iioff1  = 1        ; iioff2  = 0
+      ijoff1  = 0        ; ijoff2  = 1
+      cv_lat  =cn_gphiu
+  CASE ( 'V' )
+      ! needs fmask, tmask, e1f, e1v, e2t, e2v 
+      cmask_i = 'fmask'  ; cmask_j = 'tmask'
+      ce1_i1  = cn_ve1f  ; ce1_i2  = cn_ve1v
+      ce2_j1  = cn_ve2t  ; ce2_j2  = cn_ve2v
+      iioff1  = 0        ; iioff2  = 1
+      ijoff1  = 1        ; ijoff2  = 0
+      cv_lat  =cn_gphiv
+  CASE ( 'F' )
+      ! needs vmask, umask, e1v, e1f, e2u, e2f 
+      cmask_i = 'vmask'  ; cmask_j = 'umask'
+      ce1_i1  = cn_ve1v  ; ce1_i2  = cn_ve1f
+      ce2_j1  = cn_ve2u  ; ce2_j2  = cn_ve2f
+      iioff1  = 1        ; iioff2  = 0
+      ijoff1  = 1        ; ijoff2  = 0
+      cv_lat  =cn_gphif
+  CASE DEFAULT
+      PRINT *, ' TYPE ', TRIM(ct_in),' unknown on C-grid'
+      STOP
+  END SELECT
+      
+
+  ! Allocate the memory
+  ALLOCATE ( e1_i1(npiglo,npjglo), e2_j1(npiglo,npjglo) )
+  ALLOCATE ( e1_i2(npiglo,npjglo), e2_j2(npiglo,npjglo) )
+  ALLOCATE ( rmski(npiglo,npjglo), rmskj(npiglo,npjglo) )
+  IF ( l_overf2 ) THEN
+     ALLOCATE (  ff(npiglo,npjglo), gphi(npiglo,npjglo) )
+  ENDIF
+
+  ALLOCATE ( dlap(npiglo,npjglo), v2d(npiglo, npjglo)  )
+  ALLOCATE ( tim(npt) )
+
+  ! Read the metrics from the mesh_hgr file
+  IF ( l_metric ) THEN
+    e1_i1 = getvar(cn_fhgr, ce1_i1, 1, npiglo, npjglo)
+    e1_i2 = getvar(cn_fhgr, ce1_i2, 1, npiglo, npjglo)
+    e2_j1 = getvar(cn_fhgr, ce2_j1, 1, npiglo, npjglo)
+    e2_j2 = getvar(cn_fhgr, ce2_j2, 1, npiglo, npjglo)
+  ELSE
+    e1_i1 = 1.
+    e1_i2 = 1.
+    e2_j1 = 1.
+    e2_j2 = 1.
+  ENDIF
+!
+  IF ( l_overf2 ) THEN
+    ! to prepare computation of g/f*LAP(SSH) 
+     gphi    = getvar(cn_fhgr, cv_lat, 1, npiglo, npjglo)
+     rpi     = acos(-1.)
+     omega   = 2 * rpi / 86400.
+     ff     = 2.*omega* sin (gphi*rpi/180.)
+     WHERE (ff == 0 ) ff = epsilon(1.0)
+  ENDIF
+
+  ! create output fileset
+  ncout = create      (cf_out, cf_in, npiglo, npjglo, npk         ) 
+  ierr  = createvar   (ncout,  stypvar, 1,      ipk,    id_varout )
+  ierr  = putheadervar(ncout,  cf_in, npiglo, npjglo, npk         )
+
+  tim  = getvar1d(cf_in , cn_vtimec, npt     )
+  ierr = putvar1d(ncout , tim      , npt, 'T')
+
+  ! Main time loop
+  DO jt = 1, npt
+     ! Main level loop from top to bottom
+     DO jk = 1, npkv
+        PRINT *,'jt = ', jt,' jk = ', jk
+
+        ! variable at level jk time jt
+        v2d(:,:) =  getvar(cf_in, cv_in, jk, npiglo, npjglo, ktime=jt)
+        ! relevant mask
+        IF ( l_metric ) THEN
+        rmski = getvar(cn_fmsk, cmask_i, jk, npiglo, npjglo)
+        rmskj = getvar(cn_fmsk, cmask_j, jk, npiglo, npjglo)
+        ELSE
+        ! something can be done with regard to field's  missing value
+        rmski = 1.
+        rmskj = 1.
+        ENDIF
+        ! Compute laplacian
+        dlap(:,:) = 0.d0
+        DO jj = 2, npjglo -1
+           ij1 = jj + ijoff1
+           ij2 = jj - ijoff2
+           DO ji = 2, npiglo -1
+              ii1 = ji + iioff1
+              ii2 = ji - iioff2
+              dlap(ji,jj) =  ( ( v2d(ji+1,jj) - v2d(ji,jj) )*1.d0 /e1_i1(ii1,jj)* rmski(ii1,jj)    &
+           &  - ( v2d(ji,jj) - v2d(ji-1,jj) )*1.d0/e1_i1(ii2,jj)*  rmski(ii2,jj) ) / e1_i2(ji,jj)  &
+           &  + ( ( v2d(ji,jj+1) - v2d(ji,jj) )*1.d0 /e2_j1(ji,ij1)* rmskj(ji,ij1)                 &
+           &  - ( v2d(ji,jj) - v2d(ji,jj-1) )*1.d0/e2_j1(ji,ij2)*  rmskj(ji,ij2) ) / e2_j2(ji,jj)
+           END DO
+        END DO
+
+        IF ( l_overf2 ) THEN
+          WHERE (dlap == 0.d0 )
+            dlap = dspval
+          ELSEWHERE
+            dlap = grav*dlap /ff/ff
+          ENDWHERE
+        ENDIF
+
+        ! write level jk 
+        ierr = putvar(ncout, id_varout(1), REAL(dlap), jk, npiglo, npjglo, ktime=jt)
+
+     END DO  ! loop to next level
+  END DO ! loop on time
+
+  ierr = closeout(ncout)
+
+END PROGRAM cdflap
+
diff --git a/cdflinreg.f90 b/src/cdflinreg.f90
similarity index 100%
rename from cdflinreg.f90
rename to src/cdflinreg.f90
diff --git a/cdfmaskdmp.f90 b/src/cdfmaskdmp.f90
similarity index 98%
rename from cdfmaskdmp.f90
rename to src/cdfmaskdmp.f90
index eb3d5dc..7d48ca5 100644
--- a/cdfmaskdmp.f90
+++ b/src/cdfmaskdmp.f90
@@ -109,7 +109,7 @@ PROGRAM cdfmaskdmp
   CALL getarg (1, cf_tfil)
   CALL getarg (2, cf_sfil)
 
-  IF ( chkfile(cf_tfil) .OR. chkfile(cf_sfil) ) STOP ! missing files
+  IF ( chkfile(cf_tfil) .OR. chkfile(cf_sfil) .OR. chkfile(cn_fmsk) ) STOP ! missing files
 
   IF ( narg == 9 ) THEN
      CALL getarg (3, cldum) ; READ(cldum,*) ref_dep
diff --git a/cdfmax.f90 b/src/cdfmax.f90
similarity index 99%
rename from cdfmax.f90
rename to src/cdfmax.f90
index ebf7ba7..daa806a 100644
--- a/cdfmax.f90
+++ b/src/cdfmax.f90
@@ -144,6 +144,7 @@ PROGRAM cdfmax
         nk = getdim(cf_in, 'lev', cldum, istatus)
         IF ( istatus == 1 ) THEN
            PRINT *,' No dep or z or lev  dim found ' 
+           nk = 1
         ENDIF
      ENDIF
   ENDIF
diff --git a/cdfmaxmoc.f90 b/src/cdfmaxmoc.f90
similarity index 100%
rename from cdfmaxmoc.f90
rename to src/cdfmaxmoc.f90
diff --git a/cdfmean.f90 b/src/cdfmean.f90
similarity index 90%
rename from cdfmean.f90
rename to src/cdfmean.f90
index 2c1679b..a9dd24a 100644
--- a/cdfmean.f90
+++ b/src/cdfmean.f90
@@ -64,7 +64,7 @@ PROGRAM cdfmean
   CHARACTER(LEN=256)                         :: cv_dep             ! deptht name
   CHARACTER(LEN=20)                          :: cv_e1, cv_e2       ! horizontal metrics names
   CHARACTER(LEN=20)                          :: cv_e3, cv_e31d     ! vertical metrics names
-  CHARACTER(LEN=20)                          :: cv_msk             ! mask variable name
+  CHARACTER(LEN=20)                          :: cv_msk = ''        ! mask variable name
   CHARACTER(LEN=256)                         :: cf_in              ! input file name
   CHARACTER(LEN=256)                         :: cf_out   = 'cdfmean.txt' ! ASCII output file for mean
   CHARACTER(LEN=256)                         :: cf_var   = 'cdfvar.txt'  ! ASCII output file for variance
@@ -93,7 +93,9 @@ PROGRAM cdfmean
   narg = iargc()
   IF ( narg == 0 ) THEN
      PRINT *,' usage : cdfmean  IN-file IN-var T|U|V|F|W [imin imax jmin jmax kmin kmax]'
-     PRINT *,'       ... [-full] [-var] [-zeromean] '
+     PRINT *,'       ... [-full] [-var] [-zeromean] [-M MSK-file VAR-mask ]'
+     PRINT *,'       ... [-o OUT-file] [ -ot OUTASCII-file] [-oz ZEROMEAN-file]'
+     PRINT *,'       ... [ -ov VAR-file]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
      PRINT *,'        Computes the mean value of the field (3D, weighted). For 3D fields,'
@@ -111,10 +113,21 @@ PROGRAM cdfmean
      PRINT *,'                  if imin = 0 then ALL i are taken'
      PRINT *,'                  if jmin = 0 then ALL j are taken'
      PRINT *,'                  if kmin = 0 then ALL k are taken'
+     PRINT *,'       [-M MSK-file VAR-mask] : Allow the use of a non standard mask file '
+     PRINT *,'              with VAR-mask, instead of ',TRIM(cn_fmsk),' and ',TRIM(cv_msk)
+     PRINT *,'              This option is a usefull alternative to the previous options, when the '
+     PRINT *,'              area of interest is not ''box-like'''
      PRINT *,'       [ -full ] : compute the mean for full steps, instead of default '
      PRINT *,'                   partial steps.'
      PRINT *,'       [ -var ]  : also compute the spatial variance of cdfvar '
      PRINT *,'       [ -zeromean ] : create a file with cdfvar having a zero spatial mean.'
+     PRINT *,'       [ -o OUT-file] : specify the name of the output file instead of ',TRIM(cf_ncout)
+     PRINT *,'       [ -ot OUTASCII-file] : specify the name of the output ASCII file instead '
+     PRINT *,'                   of ',TRIM(cf_out)
+     PRINT *,'       [ -oz ZEROMEAN-file] : specify the name of the output file for option '
+     PRINT *,'                   -zeromean, instead of ', TRIM(cf_zerom)
+     PRINT *,'       [ -ov VAR-file] : specify the name of the output file for option '
+     PRINT *,'                   -var, instead of ', TRIM(cf_var)
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'       Files ', TRIM(cn_fhgr),', ', TRIM(cn_fzgr),', ', TRIM(cn_fmsk)
@@ -133,7 +146,7 @@ PROGRAM cdfmean
 
   ! Open standard output with recl=256 to avoid wrapping of long lines (ifort)
   OPEN(6,FORM='FORMATTED',RECL=256)  ! ifort
-  !  OPEN(6,FORM='FORMATTED')          ! gfortran
+ ! OPEN(6,FORM='FORMATTED')          ! gfortran
 
   cglobal = 'Partial step computation'
   ijarg = 1 ; ii = 0
@@ -147,6 +160,17 @@ PROGRAM cdfmean
         lvar = .true. 
      CASE ('-zeromean' )
         lzeromean = .true. 
+     CASE ('-o' )
+        CALL getarg(ijarg, cf_ncout ) ; ijarg = ijarg + 1
+     CASE ('-oz' )
+        CALL getarg(ijarg, cf_zerom ) ; ijarg = ijarg + 1
+     CASE ('-ov' )
+        CALL getarg(ijarg, cf_var ) ; ijarg = ijarg + 1
+     CASE ('-ot' )
+        CALL getarg(ijarg, cf_out ) ; ijarg = ijarg + 1
+     CASE ( '-M' )
+        CALL getarg ( ijarg, cn_fmsk) ; ijarg = ijarg + 1
+        CALL getarg ( ijarg, cv_msk ) ; ijarg = ijarg + 1
      CASE DEFAULT 
         ii=ii+1
         SELECT CASE (ii) 
@@ -198,7 +222,7 @@ PROGRAM cdfmean
   npjglo_fi = npjglo
   npk_fi    = npk
 
-  IF (npk   == 0 ) THEN ; lnodep = .true.;  npk = 1                  ;  ENDIF ! no depth dimension ==> 1 level
+  IF (npk   == 0 ) THEN ; lnodep = .true.;  npk = 1; npk_fi = 1      ;  ENDIF ! no depth dimension ==> 1 level
   IF (iimin /= 0 ) THEN ; npiglo = iimax -iimin + 1;  ELSE ; iimin=1 ;  ENDIF
   IF (ijmin /= 0 ) THEN ; npjglo = ijmax -ijmin + 1;  ELSE ; ijmin=1 ;  ENDIF
   IF (ikmin /= 0 ) THEN ; npk    = ikmax -ikmin + 1;  ELSE ; ikmin=1 ;  ENDIF
@@ -226,35 +250,35 @@ PROGRAM cdfmean
      cv_e2    = cn_ve2t
      cv_e3    = 'e3t_ps'
      cv_e31d  = cn_ve3t
-     cv_msk = 'tmask'
+     IF (cv_msk   == '' ) THEN ; cv_msk = 'tmask' ;  ENDIF
      cv_dep   = cn_gdept
   CASE ( 'U' )
      cv_e1    = cn_ve1u
      cv_e2    = cn_ve2u
      cv_e3    = 'e3t_ps'
      cv_e31d  = cn_ve3t
-     cv_msk = 'umask'
+     IF (cv_msk   == '' ) THEN ; cv_msk = 'umask' ;  ENDIF
      cv_dep   = cn_gdept
   CASE ( 'V' )
      cv_e1    = cn_ve1v
      cv_e2    = cn_ve2v
      cv_e3    = 'e3t_ps'
      cv_e31d  = cn_ve3t
-     cv_msk = 'vmask'
+     IF (cv_msk   == '' ) THEN ; cv_msk = 'vmask' ;  ENDIF
      cv_dep   = cn_gdept
   CASE ( 'F' )
      cv_e1    = cn_ve1f
      cv_e2    = cn_ve2f
      cv_e3    = 'e3t_ps'
      cv_e31d  = cn_ve3t
-     cv_msk = 'fmask'
+     IF (cv_msk   == '' ) THEN ; cv_msk = 'fmask' ;  ENDIF
      cv_dep   = cn_gdept
   CASE ( 'W' )
      cv_e1    = cn_ve1t
      cv_e2    = cn_ve2t
      cv_e3    = 'e3w_ps'
      cv_e31d  = cn_ve3w
-     cv_msk = 'tmask'
+     IF (cv_msk   == '' ) THEN ; cv_msk = 'tmask' ;  ENDIF
      cv_dep   = cn_gdepw
   CASE DEFAULT
      PRINT *, 'this type of variable is not known :', TRIM(ctype)
@@ -347,7 +371,7 @@ PROGRAM cdfmean
         ELSE
           e3(:,:) = getvar(cn_fzgr, cv_e3,    ik, npiglo, npjglo, kimin=iimin, kjmin=ijmin, ldiom=.TRUE.)
         ENDIF
-        ! 
+        !
         dsurf  = SUM(DBLE(          e1 * e2      * zmask))
         dvol2d = SUM(DBLE(          e1 * e2 * e3 * zmask))
         dvol   = dvol + dvol2d
@@ -454,4 +478,5 @@ PROGRAM cdfmean
  
   ENDIF
 
+
 END PROGRAM cdfmean
diff --git a/src/cdfmeshmask.f90 b/src/cdfmeshmask.f90
new file mode 100644
index 0000000..0be6ddc
--- /dev/null
+++ b/src/cdfmeshmask.f90
@@ -0,0 +1,845 @@
+PROGRAM cdfmeshmask
+  !!======================================================================
+  !!                     ***  PROGRAM  cdfmeshmask  ***
+  !!=====================================================================
+  !!  ** Purpose : build mesh mask file from bathymetry
+  !!
+  !!  ** Method  : use nemo3.6 simplified zgr_xxx routines for zps
+  !!
+  !! History : 3.0  : 10/2014  : J.M. Molines 
+  !!----------------------------------------------------------------------
+  !!----------------------------------------------------------------------
+  !!   routines      : description
+  !!----------------------------------------------------------------------
+  USE netcdf
+  USE cdfio
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2014
+  !! $Id$
+  !! Copyright (c) 2014, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+  INTEGER, PARAMETER :: wp=8
+
+  INTEGER :: narg, iargc, ijarg
+  INTEGER :: npiglo, npjglo, nkmax
+  INTEGER :: nbloc_sz=193  , nbloc=-1
+  INTEGER, DIMENSION(:), ALLOCATABLE :: nbloc_szt, njbloct
+  INTEGER, DIMENSION(:), ALLOCATABLE :: nblock_szt, nkbloct
+  INTEGER :: jbloc, ij, i1, i2, ji     !
+  INTEGER :: nperio = 0    ! closed boundary only for the time being
+  INTEGER, DIMENSION(:,:), ALLOCATABLE :: mbathy
+
+  INTEGER :: ierr
+  INTEGER :: nczgr, nchgr, ncmsk, nccoo  ! ncdif of output files
+  INTEGER :: id_dept1d, id_depw1d, id_e3t1d, id_e3w1d, id_dept, id_depw, id_e3t, id_e3w, id_mbat  ! zgr
+  INTEGER :: id_e3u, id_e3v, id_hdept, id_hdepw, id_navlat, id_navlon, id_navlev, id_time
+  INTEGER :: idx, idy, idz, idt, idvar
+  INTEGER :: id_tmsk, id_umsk, id_vmsk, id_fmsk
+  INTEGER :: id_tmsku, id_umsku, id_vmsku, id_fmsku
+
+  INTEGER :: id_lamt, id_lamu, id_lamv, id_lamf    ! hgr  copy of coordinates  !!!
+  INTEGER :: id_phit, id_phiu, id_phiv, id_phif 
+
+  INTEGER :: id_tmask, id_umask, id_vmask, id_fmask  ! mask file
+
+  REAL(wp) :: rhmin
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: bathy, rlon, rlat
+
+  REAL(wp), DIMENSION(:),   ALLOCATABLE :: gdepw_1d, gdept_1d, e3w_1d, e3t_1d
+  REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: gdept_0  ! npiglo, jbloc, jpk
+  REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: gdepw_0  ! npiglo, jbloc, jpk
+  REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: e3t_0    ! npiglo, jbloc, jpk  then npiglo, npjglo, kbloc
+  REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: e3w_0    ! npiglo, jbloc, jpk  then npiglo, npjglo, kbloc
+  REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: e3u_0    ! npiglo, jbloc, jpk  then npiglo, npjglo, kbloc
+  REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: e3v_0    ! npiglo, jbloc, jpk  then npiglo, npjglo, kbloc
+  REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: tmask    ! npiglo, npjglo, kbloc
+  REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: umask    ! npiglo, npjglo, kbloc
+  REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: vmask    ! npiglo, npjglo, kbloc
+  REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: fmask    ! npiglo, npjglo, kbloc
+
+  LOGICAL :: lchk=.FALSE.
+
+  CHARACTER(LEN=80) :: cdum
+  CHARACTER(LEN=80) :: cf_nam
+  CHARACTER(LEN=80) :: cf_bat
+  CHARACTER(LEN=80) :: cf_coo
+  CHARACTER(LEN=80) :: cf_zgr = 'cdf_mesh_zgr.nc'
+  CHARACTER(LEN=80) :: cf_hgr = 'cdf_mesh_hgr.nc'
+  CHARACTER(LEN=80) :: cf_msk = 'cdf_mask.nc'
+
+  INTEGER ::    jpk     , jpkm1
+  INTEGER  ::   nn_bathy        !: = 0/1 ,compute/read the bathymetry file
+  REAL(wp) ::   rn_bathy        !: depth of flat bottom (active if nn_bathy=0; if =0 depth=jpkm1)
+  REAL(wp) ::   rn_hmin         !: minimum ocean depth (>0) or minimum number of ocean levels (<0)
+  REAL(wp) ::   rn_e3zps_min    !: miminum thickness for partial steps (meters)
+  REAL(wp) ::   rn_e3zps_rat    !: minimum thickness ration for partial steps
+  INTEGER  ::   nn_msh          !: = 1 create a mesh-mask file
+  INTEGER  ::   nn_acc          !: = 0/1 use of the acceleration of convergence technique
+  REAL(wp) ::   rn_atfp         !: asselin time filter parameter
+  REAL(wp) ::   rn_rdt          !: time step for the dynamics (and tracer if nacc=0)
+  REAL(wp) ::   rn_rdtmin       !: minimum time step on tracers
+  REAL(wp) ::   rn_rdtmax       !: maximum time step on tracers
+  REAL(wp) ::   rn_rdth         !: depth variation of tracer step
+  INTEGER  ::   nn_closea       !: =0 suppress closed sea/lake from the ORCA domain or not (=1)
+  INTEGER  ::   nn_euler        !: =0 start with forward time step or not (=1)
+  LOGICAL  ::   ln_crs          !: Apply grid coarsening to dynamical model output or online passive tracers
+
+  INTEGER       ::   jphgr_msh        !: 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
+
+  REAL(wp)      ::   ppglam0              !: longitude of first raw and column T-point (jphgr_msh = 1)
+  REAL(wp)      ::   ppgphi0              !: latitude  of first raw and column T-point (jphgr_msh = 1)
+  !                                                        !  used for Coriolis & Beta parameters (jphgr_msh = 2 or 3)
+  REAL(wp)      ::   ppe1_deg             !: zonal      grid-spacing (degrees)
+  REAL(wp)      ::   ppe2_deg             !: meridional grid-spacing (degrees)
+  REAL(wp)      ::   ppe1_m               !: zonal      grid-spacing (degrees)
+  REAL(wp)      ::   ppe2_m               !: meridional grid-spacing (degrees)
+
+  REAL(wp)      ::   ppsur                !: ORCA r4, r2 and r05 coefficients
+  REAL(wp)      ::   ppa0                 !: (default coefficients)
+  REAL(wp)      ::   ppa1                 !:
+  REAL(wp)      ::   ppkth                !:
+  REAL(wp)      ::   ppacr                !:
+  !
+  !  If both ppa0 ppa1 and ppsur are specified to 0, then
+  !  they are computed from ppdzmin, pphmax , ppkth, ppacr in dom_zgr
+  REAL(wp)      ::   ppdzmin              !: Minimum vertical spacing
+  REAL(wp)      ::   pphmax               !: Maximum depth
+  !
+  LOGICAL       ::   ldbletanh            !: Use/do not use double tanf function for vertical coordinates
+  REAL(wp)      ::   ppa2                 !: Double tanh function parameters
+  REAL(wp)      ::   ppkth2               !:
+  REAL(wp)      ::   ppacr2               !:
+  !-----------------------------------------------------------------------------
+  narg=iargc()
+
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage :  cdfmeshmask -n namelist -b bathymetry_file  -c coordinates ...'
+     PRINT *,'         ... [-njbloc nbloc] '
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'       Create mesh_mask from bathymetry and namdom information (namelist)' 
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       -n namelist : name of the namelist file' 
+     PRINT *,'       -b bathymetry : name of bathymetry (meters)'
+     PRINT *,'       -c coordinates : name of coordinates file'
+     PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'       -njbloc nbloc : number of j-bloc of rows to treat together. Increasing'
+     PRINT *,'             nbloc decreases memory usage but increases writing time.'
+     PRINT *,'            default : nbloc = npjglo (worst condition) '
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'        namelist, bathymetry and coordinated passed on the command line' 
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf files : ', TRIM(cf_zgr) , TRIM(cf_hgr), TRIM(cf_msk)
+     PRINT *,'      '
+     PRINT *,'     SEE ALSO :'
+     PRINT *,'       '
+     PRINT *,'      '
+     STOP
+  ENDIF
+
+  ijarg=1
+  DO WHILE ( ijarg <= narg )
+     CALL getarg(ijarg, cdum) ; ijarg=ijarg+1
+     SELECT CASE ( cdum )
+     CASE ('-n ')
+        CALL getarg(ijarg,cf_nam) ; ijarg=ijarg+1
+     CASE ('-b ')
+        CALL getarg(ijarg,cf_bat) ; ijarg=ijarg+1
+     CASE ('-c ')
+        CALL getarg(ijarg,cf_coo) ; ijarg=ijarg+1
+     CASE ('-njbloc ')
+        CALL getarg(ijarg,cdum) ; ijarg=ijarg+1
+        READ(cdum,*) nbloc
+     END SELECT
+  ENDDO
+  lchk = lchk .OR. chkfile(cf_nam) 
+  lchk = lchk .OR. chkfile(cf_bat) 
+  lchk = lchk .OR. chkfile(cf_coo) 
+  IF ( lchk ) STOP ! missing files
+
+  npiglo = getdim(cf_coo, cn_x)
+  npjglo = getdim(cf_coo, cn_y)
+  IF ( nbloc == -1 ) nbloc = npjglo
+  ! build nbloc_szt and njbloct
+  ALLOCATE(  nbloc_szt(nbloc), njbloct(nbloc) )
+  i1 = npjglo/nbloc
+  i2 = mod(npjglo, nbloc )
+  nbloc_szt(1         :nbloc-i2) = i1
+  nbloc_szt(nbloc-i2+1:nbloc   ) = i1+1
+  njbloct(1) = 1
+  DO ji=2, nbloc
+     njbloct(ji) = njbloct(ji-1) + nbloc_szt(ji-1)
+  ENDDO
+
+
+  ALLOCATE (bathy(npiglo, npjglo ), rlon(npiglo, npjglo )  , rlat(npiglo, npjglo )  ) 
+  ALLOCATE (mbathy(npiglo, npjglo )) 
+
+  CALL zgr_z
+  bathy(:,:) = getvar(cf_bat, cn_bathymet, 1, npiglo, npjglo)
+  ! set minimum value here :
+  IF( rn_hmin < 0._wp ) THEN       
+     nkmax = - INT( rn_hmin )                                       ! from a nb of level
+  ELSE 
+     nkmax = MINLOC( gdepw_1d, mask = gdepw_1d > rn_hmin, dim = 1 ) ! from a depth
+  ENDIF
+  rhmin = gdepw_1d(nkmax+1)                                        ! minimum depth = ik+1 w-levels
+
+  WHERE( bathy(:,:) <= 0._wp )   
+     bathy(:,:) = 0._wp                         ! min=0     over the lands
+  ELSE WHERE                     
+     bathy(:,:) = MAX(  rhmin , bathy(:,:)  )   ! min=rhmin over the oceans
+  END WHERE
+  PRINT *,  'Minimum ocean depth: ', rhmin, ' minimum number of ocean levels : ', nkmax
+
+  CALL zgr_zps
+
+
+CONTAINS
+  SUBROUTINE zgr_z
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE zgr_z  ***
+    !!
+    !! ** Purpose :    set the depth of model levels and the resulting 
+    !!         vertical scale factors.
+    !!
+    !! ** Method  :   from NEMO 3.6
+    !!
+    !! References :  
+    !!----------------------------------------------------------------------
+    INTEGER  ::   jk                     ! dummy loop indices
+    INTEGER  ::   inum = 27              !
+    REAL(wp) ::   zt, zw                 ! temporary scalars
+    REAL(wp) ::   zsur, za0, za1, zkth   ! Values set from parameters in
+    REAL(wp) ::   zacr, zdzmin, zhmax    ! par_CONFIG_Rxx.h90
+    REAL(wp) ::   zrefdep                ! depth of the reference level (~10m)
+    REAL(wp) ::   za2, zkth2, zacr2      ! Values for optional double tanh function set from parameters 
+
+    NAMELIST/namdom/ jpk, nn_bathy , rn_bathy, rn_e3zps_min, rn_e3zps_rat, nn_msh    , rn_hmin, &
+         &             nn_acc   , rn_atfp     , rn_rdt      , rn_rdtmin,           &
+         &             rn_rdtmax, rn_rdth     , nn_closea , ln_crs,    &
+         &             jphgr_msh, &
+         &             ppglam0, ppgphi0, ppe1_deg, ppe2_deg, ppe1_m, ppe2_m, &
+         &             ppsur, ppa0, ppa1, ppkth, ppacr, ppdzmin, pphmax, ldbletanh, &
+         &             ppa2, ppkth2, ppacr2
+    !! -----------------------------------------------------------------------------------------
+    OPEN(inum, FILE=cf_nam)
+    READ(inum, namdom)
+    CLOSE(inum)
+    jpkm1=jpk-1
+
+    ! build nbloc_szt and njbloct
+    ALLOCATE(  nblock_szt(nbloc), nkbloct(nbloc) )
+    i1 = jpk/nbloc
+    i2 = mod(jpk, nbloc )
+    nblock_szt(1         :nbloc-i2) = i1
+    nblock_szt(nbloc-i2+1:nbloc   ) = i1+1
+    nkbloct(1) = 1
+    DO ji=2, nbloc
+       nkbloct(ji) = nkbloct(ji-1) + nblock_szt(ji-1)
+    ENDDO
+
+    ALLOCATE (gdept_1d(jpk), gdepw_1d(jpk), e3t_1d(jpk), e3w_1d(jpk) )
+
+    ! Set variables from parameters
+    ! ------------------------------
+    zkth = ppkth       ;   zacr = ppacr
+    zdzmin = ppdzmin   ;   zhmax = pphmax
+    zkth2 = ppkth2     ;   zacr2 = ppacr2   ! optional (ldbletanh=T) double tanh parameters
+
+    IF(   ppa1  == 999    .AND.  &
+         &  ppa0  == 999  .AND.  &
+         &  ppsur == 999         ) THEN
+       !
+       za1  = (  ppdzmin - pphmax / FLOAT(jpkm1)  )                                                      &
+            & / ( TANH((1-ppkth)/ppacr) - ppacr/FLOAT(jpk-1) * (  LOG( COSH( (jpk - ppkth) / ppacr) )      &
+            &                                                   - LOG( COSH( ( 1  - ppkth) / ppacr) )  )  )
+       za0  = ppdzmin - za1 *              TANH( (1-ppkth) / ppacr )
+       zsur =   - za0 - za1 * ppacr * LOG( COSH( (1-ppkth) / ppacr )  )
+    ELSE
+       za1 = ppa1 ;       za0 = ppa0 ;          zsur = ppsur
+       za2 = ppa2                            ! optional (ldbletanh=T) double tanh parameter
+    ENDIF
+
+    IF( .NOT. ldbletanh ) THEN
+       DO jk = 1, jpk
+          zw = REAL( jk , wp )
+          zt = REAL( jk , wp ) + 0.5_wp
+          gdepw_1d(jk) = ( zsur + za0 * zw + za1 * zacr * LOG ( COSH( (zw-zkth) / zacr ) )  )
+          gdept_1d(jk) = ( zsur + za0 * zt + za1 * zacr * LOG ( COSH( (zt-zkth) / zacr ) )  )
+          e3w_1d  (jk) =          za0      + za1        * TANH(       (zw-zkth) / zacr   )
+          e3t_1d  (jk) =          za0      + za1        * TANH(       (zt-zkth) / zacr   )
+       END DO
+    ELSE
+       DO jk = 1, jpk
+          zw = FLOAT( jk )
+          zt = FLOAT( jk ) + 0.5_wp
+          ! Double tanh function
+          gdepw_1d(jk) = ( zsur + za0 * zw + za1 * zacr * LOG ( COSH( (zw-zkth ) / zacr  ) )    &
+               &                             + za2 * zacr2* LOG ( COSH( (zw-zkth2) / zacr2 ) )  )
+          gdept_1d(jk) = ( zsur + za0 * zt + za1 * zacr * LOG ( COSH( (zt-zkth ) / zacr  ) )    &
+               &                             + za2 * zacr2* LOG ( COSH( (zt-zkth2) / zacr2 ) )  )
+          e3w_1d  (jk) =          za0      + za1        * TANH(       (zw-zkth ) / zacr  )      &
+               &                             + za2        * TANH(       (zw-zkth2) / zacr2 )
+          e3t_1d  (jk) =          za0      + za1        * TANH(       (zt-zkth ) / zacr  )      &
+               &                             + za2        * TANH(       (zt-zkth2) / zacr2 )
+       END DO
+    ENDIF
+    gdepw_1d(1) = 0._wp                    ! force first w-level to be exactly at zero
+    CALL CreateMeshZgrFile
+    CALL CreateMaskFile
+
+  END SUBROUTINE zgr_z
+
+  SUBROUTINE zgr_zps
+    !!----------------------------------------------------------------------
+    !!                  ***  ROUTINE zgr_zps  ***
+    !!                     
+    !! ** Purpose :   the depth and vertical scale factor in partial step
+    !!      z-coordinate case
+    !!
+    !! ** Method  :   Partial steps : computes the 3D vertical scale factors
+    !!      of T-, U-, V-, W-, UW-, VW and F-points that are associated with
+    !!      a partial step representation of bottom topography.
+    !!----------------------------------------------------------------------
+    INTEGER  ::   ji, jj, jk       ! dummy loop indices
+    INTEGER  ::   ik, it           ! temporary integers
+    LOGICAL  ::   ll_print         ! Allow  control print for debugging
+    REAL(wp) ::   ze3tp , ze3wp    ! Last ocean level thickness at T- and W-points
+    REAL(wp) ::   zdepwp, zdepth   ! Ajusted ocean depth to avoid too small e3t
+    REAL(wp) ::   zmax             ! Maximum depth
+    REAL(wp) ::   zdiff            ! temporary scalar
+    REAL(wp) ::   zrefdep          ! temporary scalar
+    REAL(wp), DIMENSION(:,:), ALLOCATABLE :: zdep
+    !!----------------------------------------------------------------------
+
+
+    zmax = gdepw_1d(jpk) + e3t_1d(jpk)        ! maximum depth (i.e. the last ocean level thickness <= 2*e3t_1d(jpkm1) )
+    bathy(:,:) = MIN( zmax ,  bathy(:,:) )    ! bounded value of bathy (min already set at the end of zgr_bat)
+
+    WHERE( bathy(:,:) == 0._wp )   
+       mbathy(:,:) = 0       ! land  : set mbathy to 0
+    ELSE WHERE                     
+       mbathy(:,:) = jpkm1   ! ocean : initialize mbathy to the max ocean level
+    END WHERE
+
+    ! Compute mbathy for ocean points (i.e. the number of ocean levels)
+    ! find the number of ocean levels such that the last level thickness
+    ! is larger than the minimum of e3zps_min and e3zps_rat * e3t_1d (where
+    ! e3t_1d is the reference level thickness
+    DO jk = jpkm1, 1, -1
+       zdepth = gdepw_1d(jk) + MIN( rn_e3zps_min, e3t_1d(jk)*rn_e3zps_rat )
+       WHERE( 0._wp < bathy(:,:) .AND. bathy(:,:) <= zdepth )   mbathy(:,:) = jk-1
+    END DO
+
+    CALL zgr_bat_ctl
+
+    ! compute mask from mbathy : for writing performance and memory management, each mask is computed
+    !  and written on file sequentially. Thus repeating  tmask determination (cheap)
+    DO jbloc=1, nbloc
+       nbloc_sz = nblock_szt(jbloc)
+       ALLOCATE ( tmask(npiglo, npjglo,nbloc_sz) )
+       tmask(:,:,:) = 0._wp
+       DO jk = 1, nbloc_sz
+          ik = nkbloct(jbloc) +jk -1
+          PRINT *, 'T Masks for jk = ', ik
+          DO jj = 1, npjglo
+             DO ji = 1, npiglo
+                IF( REAL( mbathy(ji,jj) - ik, wp ) + 0.1_wp >= 0._wp )   tmask(ji,jj,jk) = 1._wp
+             END DO
+          END DO
+          IF ( ik == 1 ) THEN
+             ierr = NF90_PUT_VAR( ncmsk, id_tmsku, tmask(:,:,1),    start=(/1,1,1/), count=(/npiglo,npjglo,1/) )
+             IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+             ENDIF
+          ENDIF
+       ENDDO
+       ierr = NF90_PUT_VAR( ncmsk, id_tmsk, tmask,    start=(/1,1,nkbloct(jbloc),1/), count=(/npiglo,npjglo,nbloc_sz,1/) )
+       IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ; 
+       ENDIF
+       DEALLOCATE ( tmask )
+    ENDDO ! bloc
+
+    DO jbloc=1, nbloc
+       nbloc_sz = nblock_szt(jbloc)
+       ALLOCATE ( tmask(npiglo, npjglo,nbloc_sz) )
+       ALLOCATE ( umask(npiglo, npjglo,nbloc_sz) )
+       tmask(:,:,:) = 0._wp
+       umask(:,:,:) = 0._wp
+       DO jk = 1, nbloc_sz
+          ik = nkbloct(jbloc) +jk -1
+          PRINT *, 'U Masks for jk = ', ik
+          DO jj = 1, npjglo
+             DO ji = 1, npiglo
+                IF( REAL( mbathy(ji,jj) - ik, wp ) + 0.1_wp >= 0._wp )   tmask(ji,jj,jk) = 1._wp
+             END DO
+          END DO
+          DO jj = 1, npjglo -1
+             DO ji = 1, npiglo -1
+                umask(ji,jj,jk) = tmask(ji,jj,jk) * tmask(ji+1,jj,jk  )
+             ENDDO
+          ENDDO
+          IF ( ik == 1 ) THEN
+             ierr = NF90_PUT_VAR( ncmsk, id_umsku, umask(:,:,1),    start=(/1,1,1/), count=(/npiglo,npjglo,1/) )
+             IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+             ENDIF
+          ENDIF
+       ENDDO
+       ierr = NF90_PUT_VAR( ncmsk, id_umsk, umask,    start=(/1,1,nkbloct(jbloc),1/), count=(/npiglo,npjglo,nbloc_sz,1/) )
+       IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+       ENDIF
+       DEALLOCATE ( tmask , umask)
+    ENDDO
+    DO jbloc=1, nbloc
+       nbloc_sz = nblock_szt(jbloc)
+       ALLOCATE ( tmask(npiglo, npjglo,nbloc_sz) )
+       ALLOCATE ( vmask(npiglo, npjglo,nbloc_sz) )
+       tmask(:,:,:) = 0._wp
+       vmask(:,:,:) = 0._wp
+
+       DO jk = 1, nbloc_sz
+          ik = nkbloct(jbloc) +jk -1
+          PRINT *, 'V Masks for jk = ', ik
+          DO jj = 1, npjglo
+             DO ji = 1, npiglo
+                IF( REAL( mbathy(ji,jj) - ik, wp ) + 0.1_wp >= 0._wp )   tmask(ji,jj,jk) = 1._wp
+             END DO
+          END DO
+          DO jj = 1, npjglo -1
+             DO ji = 1, npiglo -1
+                vmask(ji,jj,jk) = tmask(ji,jj,jk) * tmask(ji  ,jj+1,jk)
+             ENDDO
+          ENDDO
+          IF ( ik == 1 ) THEN
+             ierr = NF90_PUT_VAR( ncmsk, id_vmsku, vmask(:,:,1),    start=(/1,1,1/), count=(/npiglo,npjglo,1/) )
+             IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+             ENDIF
+          ENDIF
+       ENDDO
+       ierr = NF90_PUT_VAR( ncmsk, id_vmsk, vmask,    start=(/1,1,nkbloct(jbloc),1/), count=(/npiglo,npjglo,nbloc_sz,1/) )
+       IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+       ENDIF
+       DEALLOCATE ( tmask , vmask)
+    ENDDO
+
+    DO jbloc=1, nbloc
+       nbloc_sz = nblock_szt(jbloc)
+       ALLOCATE ( tmask(npiglo, npjglo,nbloc_sz) )
+       ALLOCATE ( fmask(npiglo, npjglo,nbloc_sz) )
+       tmask(:,:,:) = 0._wp
+       fmask(:,:,:) = 0._wp
+
+       DO jk = 1, nbloc_sz
+          ik = nkbloct(jbloc) +jk -1
+          PRINT *, 'F Masks for jk = ', ik
+          DO jj = 1, npjglo
+             DO ji = 1, npiglo
+                IF( REAL( mbathy(ji,jj) - ik, wp ) + 0.1_wp >= 0._wp )   tmask(ji,jj,jk) = 1._wp
+             END DO
+          END DO
+          DO jj = 1, npjglo -1
+             DO ji = 1, npiglo -1
+                fmask(ji,jj,jk) = tmask(ji,jj,jk  ) * tmask(ji+1,jj,jk  )   &
+                     &  * tmask(ji,jj+1,jk) * tmask(ji+1,jj+1,jk)
+             ENDDO
+          ENDDO
+          IF ( ik == 1 ) THEN
+             ierr = NF90_PUT_VAR( ncmsk, id_fmsku, fmask(:,:,1),    start=(/1,1,1/), count=(/npiglo,npjglo,1/) )
+             IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+             ENDIF
+          ENDIF
+       ENDDO
+       ierr = NF90_PUT_VAR( ncmsk, id_fmsk, fmask,    start=(/1,1,nkbloct(jbloc),1/), count=(/npiglo,npjglo,nbloc_sz,1/) )
+       IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+       ENDIF
+       DEALLOCATE ( tmask , fmask)
+    ENDDO
+
+    ierr = NF90_CLOSE(ncmsk)
+
+    ! Now work for vertical metrics
+    DO jbloc=1,nbloc
+       PRINT *, ' WORKING for jbloc-slab ', jbloc
+       nbloc_sz = nbloc_szt(jbloc)
+       ALLOCATE ( gdept_0(npiglo,nbloc_sz, jpk) )
+       ALLOCATE ( gdepw_0(npiglo,nbloc_sz, jpk) )
+       ALLOCATE ( zdep(npiglo,nbloc_sz) )
+       ALLOCATE ( e3t_0(npiglo,nbloc_sz, jpk) )
+       ALLOCATE ( e3w_0(npiglo,nbloc_sz, jpk) )
+       DO jk=1, jpk
+          gdept_0(:,:,jk) = gdept_1d(jk)
+          gdepw_0(:,:,jk) = gdepw_1d(jk)
+          e3t_0  (:,:,jk) = e3t_1d  (jk)
+          e3w_0  (:,:,jk) = e3w_1d  (jk)
+       ENDDO
+       DO jj=1, nbloc_sz
+          ij=njbloct(jbloc) + jj - 1
+          DO ji=1, npiglo
+             ik = mbathy(ji,ij)
+             IF( ik > 0 ) THEN               ! ocean point only
+                ! max ocean level case
+                IF( ik == jpkm1 ) THEN
+                   zdepwp = bathy(ji,ij)
+                   ze3tp  = bathy(ji,ij) - gdepw_1d(ik)
+                   ze3wp = 0.5_wp * e3w_1d(ik) * ( 1._wp + ( ze3tp/e3t_1d(ik) ) )
+                   e3t_0(ji,jj,ik  ) = ze3tp
+                   e3t_0(ji,jj,ik+1) = ze3tp
+                   e3w_0(ji,jj,ik  ) = ze3wp
+                   e3w_0(ji,jj,ik+1) = ze3tp
+                   gdepw_0(ji,jj,ik+1) = zdepwp
+                   gdept_0(ji,jj,ik  ) = gdept_1d(ik-1) + ze3wp
+                   gdept_0(ji,jj,ik+1) = gdept_0(ji,jj,ik) + ze3tp
+                   !
+                ELSE                         ! standard case
+                   IF( bathy(ji,ij) <= gdepw_1d(ik+1) ) THEN  ;   gdepw_0(ji,jj,ik+1) = bathy(ji,ij)
+                   ELSE                                       ;   gdepw_0(ji,jj,ik+1) = gdepw_1d(ik+1)
+                   ENDIF
+                   !       ... on ik
+                   gdept_0(ji,jj,ik) = gdepw_1d(ik) + ( gdepw_0   (ji,jj,ik+1) - gdepw_1d(ik) )   &
+                        &                          * ((gdept_1d(     ik  ) - gdepw_1d(ik) )   &
+                        &                           /( gdepw_1d(     ik+1) - gdepw_1d(ik) ))
+                   e3t_0(ji,jj,ik) = e3t_1d (ik)    * ( gdepw_0   (ji,jj,ik+1) - gdepw_1d(ik) )   &
+                        &                          / ( gdepw_1d(     ik+1) - gdepw_1d(ik) )
+                   e3w_0(ji,jj,ik) = 0.5_wp * ( gdepw_0(ji,jj,ik+1) + gdepw_1d(ik+1) - 2._wp * gdepw_1d(ik) )   &
+                        &                  * ( e3w_1d(ik) / ( gdepw_1d(ik+1) - gdepw_1d(ik) ) )
+                   !       ... on ik+1
+                   e3w_0  (ji,jj,ik+1) = e3t_0  (ji,jj,ik)
+                   e3t_0  (ji,jj,ik+1) = e3t_0  (ji,jj,ik)
+                   gdept_0(ji,jj,ik+1) = gdept_0(ji,jj,ik) + e3t_0(ji,jj,ik)
+                ENDIF
+             ENDIF
+          END DO
+       ENDDO
+
+       ! write mesh_zgr here with gdept_0, gdepw_0, e3t_0, e3w_0 only
+       ! do it quick and dirty at this time ...
+       ! write vertical slab (maybe slow but save lot of memory
+       DO jj=1, nbloc_sz
+!         ij=(jbloc -1 )*nbloc_sz +jj
+          ij=njbloct(jbloc) + jj - 1
+          DO ji = 1, npiglo
+             ik=MAX( mbathy(ji,ij),1)
+             zdep(ji,jj)=gdept_0(ji,jj,ik) 
+          ENDDO
+       ENDDO
+       ierr = NF90_PUT_VAR( nczgr, id_hdept, zdep,    start=(/1,(jbloc-1)*nbloc_sz+1  ,1/), count=(/npiglo,nbloc_sz    ,1/) )
+
+       DO jj=1, nbloc_sz
+!         ij=(jbloc -1 )*nbloc_sz +jj
+          ij=njbloct(jbloc) + jj - 1
+          DO ji = 1, npiglo
+             ik=MAX( mbathy(ji,ij),1)
+             zdep(ji,jj)=gdepw_0(ji,jj,ik+1) 
+          ENDDO
+       ENDDO
+       ierr = NF90_PUT_VAR( nczgr, id_hdepw, zdep,    start=(/1,(jbloc-1)*nbloc_sz+1  ,1/), count=(/npiglo,nbloc_sz    ,1/) )
+
+       ierr = NF90_PUT_VAR( nczgr, id_e3t, e3t_0,    start=(/1,(jbloc-1)*nbloc_sz+1,1,1/), count=(/npiglo,nbloc_sz,jpk,1/) )
+       ierr = NF90_PUT_VAR( nczgr, id_e3w, e3w_0,    start=(/1,(jbloc-1)*nbloc_sz+1,1,1/), count=(/npiglo,nbloc_sz,jpk,1/) )
+
+       DEALLOCATE ( gdept_0,  gdepw_0, zdep, e3t_0,  e3w_0 )
+    END DO
+    ierr = NF90_CLOSE(nczgr )
+
+    ! re open mesh_zgr in order to read e3t, e3w horizontally and compute e3u, e3v level by level
+    !  use rlon, rlat as temporary arrays for e3t, e3w, e3u, e3v ...
+    ierr = NF90_OPEN(cf_zgr,NF90_WRITE,nczgr )
+    ierr = NF90_INQ_VARID(nczgr,'e3t',id_e3t )
+    ierr = NF90_INQ_VARID(nczgr,'e3w',id_e3w ) 
+    ierr = NF90_INQ_VARID(nczgr,'e3u',id_e3u )
+    ierr = NF90_INQ_VARID(nczgr,'e3v',id_e3v )
+
+    DO jbloc=1, nbloc
+       nbloc_sz = nblock_szt(jbloc)
+       ALLOCATE ( e3t_0(npiglo, npjglo,nbloc_sz) )
+       ALLOCATE ( e3u_0 (npiglo, npjglo,nbloc_sz) )
+       ierr= NF90_GET_VAR( nczgr, id_e3t, e3t_0, start=(/1,1,nkbloct(jbloc),1/), count=(/npiglo,npjglo,nbloc_sz,1/) )
+
+       DO jk = 1, nbloc_sz
+          ik = nkbloct(jbloc) +jk -1
+          PRINT *,' e3u at level ', ik
+          e3u_0(:,:,jk) =  e3t_1d(ik)
+          DO jj=1,npjglo - 1
+             DO ji=1,npiglo -1
+                e3u_0(ji,jj,jk) = MIN( e3t_0(ji,jj,jk), e3t_0(ji+1,jj,jk) )
+             ENDDO
+          ENDDO
+!         ierr = NF90_PUT_VAR(nczgr, id_e3u, e3u_0, start=(/1,1,ik,1/), count=(/npiglo,npjglo,1,1/) )
+       ENDDO
+       ierr = NF90_PUT_VAR(nczgr, id_e3u, e3u_0, start=(/1,1,nkbloct(jbloc),1/), count=(/npiglo,npjglo,nbloc_sz,1/) )
+       DEALLOCATE (e3t_0, e3u_0 )
+    ENDDO
+
+    DO jbloc=1, nbloc
+       nbloc_sz = nblock_szt(jbloc)
+       ALLOCATE ( e3t_0(npiglo, npjglo,nbloc_sz) )
+       ALLOCATE ( e3v_0 (npiglo, npjglo,nbloc_sz) )
+       ierr= NF90_GET_VAR( nczgr, id_e3t, e3t_0, start=(/1,1,nkbloct(jbloc),1/), count=(/npiglo,npjglo,nbloc_sz,1/) )
+
+       DO jk = 1, nbloc_sz
+          ik = nkbloct(jbloc) +jk -1
+          PRINT *,' e3v at level ', ik
+          e3v_0(:,:,jk) =  e3t_1d(ik)
+          DO jj=1,npjglo - 1
+             DO ji=1,npiglo -1
+                e3v_0(ji,jj,jk) = MIN( e3t_0(ji,jj,jk), e3t_0(ji,jj+1,jk) )
+             ENDDO
+          ENDDO
+            print * , 'e3v_0 (81,2)  e3t_0(81,2), (81,3)', e3v_0(81,2,jk), e3t_0(81,2,jk) ,e3t_0(81,3,jk) 
+!          ierr = NF90_PUT_VAR(nczgr, id_e3v, e3v_0, start=(/1,1,ik,1/), count=(/npiglo,npjglo,1,1/) )
+       ENDDO
+       ierr = NF90_PUT_VAR(nczgr, id_e3v, e3v_0, start=(/1,1,nkbloct(jbloc),1/), count=(/npiglo,npjglo,nbloc_sz,1/) )
+       DEALLOCATE (e3t_0, e3v_0 )
+    ENDDO
+
+    ierr = NF90_CLOSE(nczgr )
+
+  END SUBROUTINE zgr_zps
+
+  SUBROUTINE zgr_bat_ctl
+    !!----------------------------------------------------------------------
+    !!                    ***  ROUTINE zgr_bat_ctl  ***
+    !!
+    !! ** Purpose :   check the bathymetry in levels
+    !!
+    !! ** Method  :   The array mbathy is checked to verified its consistency
+    !!      with the model options. in particular:
+    !!            mbathy must have at least 1 land grid-points (mbathy<=0)
+    !!                  along closed boundary.
+    !!            mbathy must be cyclic IF jperio=1.
+    !!            mbathy must be lower or equal to jpk-1.
+    !!            isolated ocean grid points are suppressed from mbathy
+    !!                  since they are only connected to remaining
+    !!                  ocean through vertical diffusion.
+    !!      C A U T I O N : mbathy will be modified during the initializa-
+    !!      tion phase to become the number of non-zero w-levels of a water
+    !!      column, with a minimum value of 1.
+    !!
+    !! ** Action  : - update mbathy: level bathymetry (in level index)
+    !!              - update bathy : meter bathymetry (in meters)
+    !!----------------------------------------------------------------------
+    !!
+    INTEGER ::   ji, jj, jl                    ! dummy loop indices
+    INTEGER ::   icompt, ibtest, ikmax         ! temporary integers
+    !!----------------------------------------------------------------------
+    icompt = 0
+    DO jl = 1, 2
+       IF( nperio == 1 .OR. nperio  ==  4 .OR. nperio  ==  6 ) THEN
+          mbathy( 1 ,:) = mbathy(npiglo-1,:)           ! local domain is cyclic east-west
+          mbathy(npiglo,:) = mbathy(  2  ,:)
+       ENDIF
+       DO jj = 2, npjglo-1
+          DO ji = 2, npiglo-1
+             ibtest = MAX(  mbathy(ji-1,jj), mbathy(ji+1,jj),   &
+                  &           mbathy(ji,jj-1), mbathy(ji,jj+1)  )
+             IF( ibtest < mbathy(ji,jj) ) THEN
+                PRINT *, ' the number of ocean level at ',   &
+                     &   'grid-point (i,j) =  ',ji,jj,' is changed from ', mbathy(ji,jj),' to ', ibtest
+                mbathy(ji,jj) = ibtest
+                icompt = icompt + 1
+             ENDIF
+          END DO
+       END DO
+    END DO
+    PRINT *, icompt,' ocean grid points suppressed'
+
+    !                                          ! East-west cyclic boundary conditions
+    IF( nperio == 0 ) THEN
+       PRINT *, ' mbathy set to 0 along east and west boundary: nperio = ', nperio
+       mbathy( 1 ,:) = 0
+       mbathy(npiglo,:) = 0
+    ELSEIF( nperio == 1 .OR. nperio == 4 .OR. nperio ==  6 ) THEN
+       PRINT *, ' east-west cyclic boundary conditions on mbathy: nperio = ', nperio
+       mbathy( 1 ,:) = mbathy(npiglo-1,:)
+       mbathy(npiglo,:) = mbathy(  2  ,:)
+    ELSEIF( nperio == 2 ) THEN
+       PRINT *, '   equatorial boundary conditions on mbathy: nperio = ', nperio
+    ELSE
+       PRINT *, '    e r r o r'
+       PRINT *, '    parameter , nperio = ', nperio
+       STOP ' '
+    ENDIF
+
+    ! write mbathy to file mesh_zgr
+    ierr = NF90_PUT_VAR( nczgr, id_mbat, mbathy, start=(/1,1,1/), count=(/npiglo,npjglo,1/) )
+
+  END SUBROUTINE zgr_bat_ctl
+
+  SUBROUTINE CreateMeshZgrFile
+    !netcdf ORCA12.L75-MAL83_mesh_zgr {
+    !dimensions:
+    !	x = 4322 ;
+    !	y = 3059 ;
+    !	z = 75 ;
+    !	t = UNLIMITED ; // (1 currently)
+    !variables:
+    !	float nav_lon(y, x) ;
+    !	float nav_lat(y, x) ;
+    !	float nav_lev(z) ;
+    !	float time_counter(t) ;
+    !	float gdept_0(t, z) ;
+    !	float gdepw_0(t, z) ;
+    !	float e3t_0(t, z) ;
+    !	float e3w_0(t, z) ;
+    !	float mbathy(t, y, x) ;
+    !	float hdept(t, y, x) ;
+    !	float hdepw(t, y, x) ;
+    !	float e3t(t, z, y, x) ;
+    !	float e3u(t, z, y, x) ;
+    !	float e3v(t, z, y, x) ;
+    !	float e3w(t, z, y, x) ;
+    !  ierr= NF90_CREATE(cf_zgr, or(NF90_CLOBBER,NF90_64BIT_OFFSET), nczgr) 
+
+    ierr= NF90_CREATE(cf_zgr, or(NF90_CLOBBER,NF90_NETCDF4), nczgr) 
+    ierr= NF90_DEF_DIM(nczgr, 'x', npiglo, idx)
+    ierr= NF90_DEF_DIM(nczgr, 'y', npjglo, idy)
+    ierr= NF90_DEF_DIM(nczgr, 'z', jpk,    idz)
+    ierr= NF90_DEF_DIM(nczgr, 't', NF90_UNLIMITED,  idt)
+
+    ierr=NF90_DEF_VAR(nczgr, 'nav_lon',       NF90_FLOAT, (/idx,idy/), id_navlon )
+    ierr=NF90_DEF_VAR(nczgr, 'nav_lat',       NF90_FLOAT, (/idx,idy/), id_navlat )
+    ierr=NF90_DEF_VAR(nczgr, 'nav_lev',       NF90_FLOAT, (/idz/)    , id_navlev )
+    ierr=NF90_DEF_VAR(nczgr, 'time_counter',  NF90_FLOAT, (/idt/)    , id_time   )
+
+    ierr=NF90_DEF_VAR(nczgr, 'gdept_0',       NF90_FLOAT, (/idz,idt/), id_dept1d )
+    ierr=NF90_DEF_VAR(nczgr, 'gdepw_0',       NF90_FLOAT, (/idz,idt/), id_depw1d )
+    ierr=NF90_DEF_VAR(nczgr, 'e3t_0',         NF90_FLOAT, (/idz,idt/), id_e3t1d  )
+    ierr=NF90_DEF_VAR(nczgr, 'e3w_0',         NF90_FLOAT, (/idz,idt/), id_e3w1d  )
+
+    ierr=NF90_DEF_VAR(nczgr, 'mbathy',        NF90_FLOAT, (/idx,idy,idt/), id_mbat )
+    ierr=NF90_DEF_VAR(nczgr, 'hdept',         NF90_FLOAT, (/idx,idy,idt/), id_hdept )
+    ierr=NF90_DEF_VAR(nczgr, 'hdepw',         NF90_FLOAT, (/idx,idy,idt/), id_hdepw )
+
+    ierr=NF90_DEF_VAR(nczgr, 'e3t',           NF90_FLOAT, (/idx,idy,idz,idt/), id_e3t )
+    ierr=NF90_DEF_VAR(nczgr, 'e3w',           NF90_FLOAT, (/idx,idy,idz,idt/), id_e3w )
+    ierr=NF90_DEF_VAR(nczgr, 'e3u',           NF90_FLOAT, (/idx,idy,idz,idt/), id_e3u )
+    ierr=NF90_DEF_VAR(nczgr, 'e3v',           NF90_FLOAT, (/idx,idy,idz,idt/), id_e3v )
+
+    ierr = NF90_ENDDEF(nczgr)
+    ! put dimension related variables
+    ierr = NF90_OPEN(cf_coo, NF90_NOCLOBBER, nccoo )
+    ierr = NF90_INQ_VARID(nccoo, cn_glamt, idvar ) ; ierr=NF90_GET_VAR(nccoo, idvar, rlon )
+    ierr = NF90_INQ_VARID(nccoo, cn_gphit, idvar ) ; ierr=NF90_GET_VAR(nccoo, idvar, rlat )
+    ierr = NF90_CLOSE(nccoo )
+
+    ierr = NF90_PUT_VAR(nczgr, id_navlon, rlon)
+    ierr = NF90_PUT_VAR(nczgr, id_navlat, rlat)
+    ierr = NF90_PUT_VAR(nczgr, id_navlev, gdept_1d )
+    ierr = NF90_PUT_VAR(nczgr, id_time  , (/0./) )
+
+    ! put 1D vertical variables (reference depth)
+    ierr = NF90_PUT_VAR(nczgr, id_dept1d, gdept_1d, start=(/1,1/), count=(/jpk,1/) )
+    ierr = NF90_PUT_VAR(nczgr, id_depw1d, gdepw_1d, start=(/1,1/), count=(/jpk,1/) )
+    ierr = NF90_PUT_VAR(nczgr, id_e3t1d,  e3t_1d,   start=(/1,1/), count=(/jpk,1/) )
+    ierr = NF90_PUT_VAR(nczgr, id_e3w1d,  e3w_1d,   start=(/1,1/), count=(/jpk,1/) )
+
+  END SUBROUTINE CreateMeshZgrFile
+
+  SUBROUTINE CreateMaskFile
+    !netcdf ORCA025.L75-MJM101.1_byte_mask {
+    !dimensions:
+    !	x = 1442 ;
+    !	y = 1021 ;
+    !	z = 75 ;
+    !	t = UNLIMITED ; // (1 currently)
+    !variables:
+    !	float nav_lon(y, x) ;
+    !	float nav_lat(y, x) ;
+    !	float nav_lev(z) ;
+    !	float time_counter(t) ;
+    !	byte tmaskutil(t, y, x) ;
+    !	byte umaskutil(t, y, x) ;
+    !	byte vmaskutil(t, y, x) ;
+    !	byte fmaskutil(t, y, x) ;
+    !	byte tmask(t, z, y, x) ;
+    !	byte umask(t, z, y, x) ;
+    !	byte vmask(t, z, y, x) ;
+    !	byte fmask(t, z, y, x) ;
+
+    ierr= NF90_CREATE(cf_msk, or(NF90_CLOBBER,NF90_NETCDF4), ncmsk) 
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+    ierr= NF90_DEF_DIM(ncmsk, 'x', npiglo, idx)
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+    ierr= NF90_DEF_DIM(ncmsk, 'y', npjglo, idy)
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+    ierr= NF90_DEF_DIM(ncmsk, 'z', jpk,    idz)
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+    ierr= NF90_DEF_DIM(ncmsk, 't', NF90_UNLIMITED,  idt)
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+
+    ierr=NF90_DEF_VAR(ncmsk, 'nav_lon',       NF90_FLOAT, (/idx,idy/), id_navlon )
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+    ierr=NF90_DEF_VAR(ncmsk, 'nav_lat',       NF90_FLOAT, (/idx,idy/), id_navlat )
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+    ierr=NF90_DEF_VAR(ncmsk, 'nav_lev',       NF90_FLOAT, (/idz/)    , id_navlev )
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+    ierr=NF90_DEF_VAR(ncmsk, 'time_counter',  NF90_FLOAT, (/idt/)    , id_time   )
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+
+    ierr=NF90_DEF_VAR(ncmsk, 'tmaskutil',    NF90_BYTE, (/idx,idy,idt/), id_tmsku )
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+    ierr=NF90_DEF_VAR(ncmsk, 'umaskutil',    NF90_BYTE, (/idx,idy,idt/), id_umsku )
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+    ierr=NF90_DEF_VAR(ncmsk, 'vmaskutil',    NF90_BYTE, (/idx,idy,idt/), id_vmsku )
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+    ierr=NF90_DEF_VAR(ncmsk, 'fmaskutil',    NF90_BYTE, (/idx,idy,idt/), id_fmsku )
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+
+    ierr=NF90_DEF_VAR(ncmsk, 'tmask',         NF90_BYTE, (/idx,idy,idz,idt/), id_tmsk )
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ; 
+    ENDIF
+    ierr=NF90_DEF_VAR(ncmsk, 'umask',         NF90_BYTE, (/idx,idy,idz,idt/), id_umsk )
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+    ierr=NF90_DEF_VAR(ncmsk, 'vmask',         NF90_BYTE, (/idx,idy,idz,idt/), id_vmsk )
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+    ierr=NF90_DEF_VAR(ncmsk, 'fmask',         NF90_BYTE, (/idx,idy,idz,idt/), id_fmsk )
+
+    ierr = NF90_ENDDEF(ncmsk)
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ; 
+    ENDIF
+    ! put dimension related variables
+
+    ierr = NF90_PUT_VAR(ncmsk, id_navlon, rlon)
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+    ierr = NF90_PUT_VAR(ncmsk, id_navlat, rlat)
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+    ierr = NF90_PUT_VAR(ncmsk, id_navlev, gdept_1d )
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+    ierr = NF90_PUT_VAR(ncmsk, id_time  , (/0./) )
+    IF ( ierr /= NF90_NOERR ) THEN  ; PRINT *, NF90_STRERROR(ierr) ; STOP ;
+    ENDIF
+
+  END SUBROUTINE CreateMaskFile
+
+
+END PROGRAM cdfmeshmask
diff --git a/cdfmhst.f90 b/src/cdfmhst.f90
similarity index 73%
rename from cdfmhst.f90
rename to src/cdfmhst.f90
index a0bd6ae..0fba492 100644
--- a/cdfmhst.f90
+++ b/src/cdfmhst.f90
@@ -106,7 +106,7 @@ PROGRAM cdfmhst
   narg= iargc()
   IF ( narg == 0 ) THEN
      PRINT *,' usage : cdfmhst  VT-file | (V-file T-file [S-file])  [MST] [-full] ...'
-     PRINT *,'              ...  [-Zdim] '
+     PRINT *,'              ...  [-Zdim] [-o OUT-file]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
      PRINT *,'       Compute the meridional heat/salt transport as a function of '
@@ -125,6 +125,7 @@ PROGRAM cdfmhst
      PRINT *,'                  If not specified, only the MHT is output.' 
      PRINT *,'       [-full ] : to be set for full step case.'
      PRINT *,'       [-Zdim ] : to be set to output vertical structure of Heat/salt transport'
+     PRINT *,'       [-o OUT-file ] : change name of the output file. Default:', TRIM(cf_outnc)
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'        ', TRIM(cn_fhgr),', ',TRIM(cn_fzgr),' and ',TRIM(cn_fmsk)
@@ -134,16 +135,16 @@ PROGRAM cdfmhst
      PRINT *,'     OUTPUT : '
      PRINT *,'       ASCII files : ', TRIM(cf_outh),' : Meridional Heat Transport'
      PRINT *,'                     ', TRIM(cf_outs),' : Meridional Salt Transport'
-     PRINT *,'       netcdf file : ', TRIM(cf_outnc)
+     PRINT *,'       netcdf file : ', TRIM(cf_outnc),' unless -o option is used.'
      PRINT *,'           variables : ( [... ] : MST option ) '
      PRINT *,'                       ', TRIM(cv_zomht),cbasin(1),' : Meridional Heat Transport (global)'
      PRINT *,'                     [ ', TRIM(cv_zomst),cbasin(1),' : Meridional Salt Transport (global) ] '
      PRINT *,'       If ',TRIM(cn_fbasins),' is available, per basin meridional transport '
      PRINT *,'       are also available:' 
-              DO jbasins=2, 6
-     PRINT *,'                       ', TRIM(cv_zomht),cbasin(jbasins),' : Meridional Heat Transport'
-     PRINT *,'                     [ ', TRIM(cv_zomst),cbasin(jbasins),' : Meridional Salt Transport ]'
-              END DO
+     DO jbasins=2, 6
+        PRINT *,'                       ', TRIM(cv_zomht),cbasin(jbasins),' : Meridional Heat Transport'
+        PRINT *,'                     [ ', TRIM(cv_zomst),cbasin(jbasins),' : Meridional Salt Transport ]'
+     END DO
      STOP
   ENDIF
 
@@ -158,13 +159,14 @@ PROGRAM cdfmhst
      CASE ( 'MST' )   ; npvar    = 2
      CASE ( '-full' ) ; lfull    = .TRUE.
      CASE ( '-Zdim' ) ; lzdim    = .TRUE.
+     CASE ( '-o'    ) ; CALL getarg(ijarg, cf_outnc) ; ijarg = ijarg+1
      CASE DEFAULT     ; ifile = ifile + 1
-          SELECT CASE (ifile)
-          CASE ( 1) ; cf_vtfil = cldum
-          CASE ( 2) ; cf_tfil  = cldum
-          CASE ( 3) ; cf_sfil  = cldum
-          CASE DEFAULT ; PRINT *,' WARNING: more than 3 files in input : weird '
-          END SELECT
+        SELECT CASE (ifile)
+        CASE ( 1) ; cf_vtfil = cldum
+        CASE ( 2) ; cf_tfil  = cldum
+        CASE ( 3) ; cf_sfil  = cldum
+        CASE DEFAULT ; PRINT *,' WARNING: more than 3 files in input : weird '
+        END SELECT
      END SELECT
   END DO
 
@@ -258,7 +260,7 @@ PROGRAM cdfmhst
   ! Allocate output variables
   ALLOCATE(stypvar(nbasinso*npvar),  cvarname(nbasinso*npvar) )
   ALLOCATE(    ipk(nbasinso*npvar), id_varout(nbasinso*npvar) )
-  
+
   ipk(:)=npko               ! all output variables either 1 or npko levels
   DO jbasins = 1,nbasinso
      cvarname(jbasins)                  = TRIM(cv_zomht)//TRIM(cbasin(jbasins))
@@ -307,11 +309,11 @@ PROGRAM cdfmhst
         PRINT *,'level ',jk
         ! Get temperature and salinity at jk
         IF ( lsepf ) THEN
-          zv(:,:)= getvar(cf_vfil, cn_vomecrty, jk, npiglo, npjglo, ktime=jt)
-          zt(:,:)= getvar(cf_tfil, cn_votemper, jk, npiglo, npjglo, ktime=jt)
-          zs(:,:)= getvar(cf_sfil, cn_vosaline, jk, npiglo, npjglo, ktime=jt)
-          zvt(:,:)=0.
-          zvs(:,:)=0.
+           zv(:,:)= getvar(cf_vfil, cn_vomecrty, jk, npiglo, npjglo, ktime=jt)
+           zt(:,:)= getvar(cf_tfil, cn_votemper, jk, npiglo, npjglo, ktime=jt)
+           zs(:,:)= getvar(cf_sfil, cn_vosaline, jk, npiglo, npjglo, ktime=jt)
+           zvt(:,:)=0.
+           zvs(:,:)=0.
            DO ji=1, npiglo
               DO jj = 1, npjglo -1
                  zvt(ji,jj) = 0.5 * ( zt(ji,jj) + zt(ji,jj+1) )*zv(ji,jj)  ! temper at Vpoint
@@ -320,8 +322,8 @@ PROGRAM cdfmhst
            END DO
 
         ELSE
-          zvt(:,:)= getvar(cf_vtfil, cn_vomevt, jk, npiglo, npjglo, ktime=jt)
-          zvs(:,:)= getvar(cf_vtfil, cn_vomevs, jk, npiglo, npjglo, ktime=jt)
+           zvt(:,:)= getvar(cf_vtfil, cn_vomevt, jk, npiglo, npjglo, ktime=jt)
+           zvs(:,:)= getvar(cf_vtfil, cn_vomevs, jk, npiglo, npjglo, ktime=jt)
         ENDIF
         ! get e3v at level jk
         IF ( lfull ) THEN
@@ -337,124 +339,124 @@ PROGRAM cdfmhst
         dtrps(:,:) = dtrps(:,:) + dwks(:,:)  
 
 
-     !global
-     zmask(:,:) = getvar(cn_fmsk, 'vmask', 1, npiglo, npjglo)
-     DO jj=1,npjglo
-        dzonal_heat_glo(jj) = SUM( dtrph(2:npiglo-1,jj)*zmask(2:npiglo-1,jj) )
-        dzonal_salt_glo(jj) = SUM( dtrps(2:npiglo-1,jj)*zmask(2:npiglo-1,jj) )
-     END DO
-
-     IF ( llglo ) THEN
-        ! Zonal mean with mask
-        ! Atlantic 
-        zmask(:,:) = getvar(cn_fbasins, 'tmaskatl', 1, npiglo, npjglo)
+        !global
+        zmask(:,:) = getvar(cn_fmsk, 'vmask', 1, npiglo, npjglo)
         DO jj=1,npjglo
-           dzonal_heat_atl(jj) = SUM( dtrph(:,jj)*zmask(:,jj) )
-           dzonal_salt_atl(jj) = SUM( dtrps(:,jj)*zmask(:,jj) )
+           dzonal_heat_glo(jj) = SUM( dtrph(2:npiglo-1,jj)*zmask(2:npiglo-1,jj) )
+           dzonal_salt_glo(jj) = SUM( dtrps(2:npiglo-1,jj)*zmask(2:npiglo-1,jj) )
         END DO
 
-        ! Pacific
-        zmask(:,:) = getvar(cn_fbasins, 'tmaskpac', 1, npiglo, npjglo)
-        DO jj=1,npjglo
-           dzonal_heat_pac(jj) = SUM( dtrph(:,jj)*zmask(:,jj) )
-           dzonal_salt_pac(jj) = SUM( dtrps(:,jj)*zmask(:,jj) )
-        END DO
+        IF ( llglo ) THEN
+           ! Zonal mean with mask
+           ! Atlantic 
+           zmask(:,:) = getvar(cn_fbasins, 'tmaskatl', 1, npiglo, npjglo)
+           DO jj=1,npjglo
+              dzonal_heat_atl(jj) = SUM( dtrph(:,jj)*zmask(:,jj) )
+              dzonal_salt_atl(jj) = SUM( dtrps(:,jj)*zmask(:,jj) )
+           END DO
 
-        ! Indian
-        zmask(:,:) = getvar(cn_fbasins, 'tmaskind', 1, npiglo, npjglo)
-        DO jj=1,npjglo
-           dzonal_heat_ind(jj) = SUM( dtrph(:,jj)*zmask(:,jj) )
-           dzonal_salt_ind(jj) = SUM( dtrps(:,jj)*zmask(:,jj) )
-        END DO
+           ! Pacific
+           zmask(:,:) = getvar(cn_fbasins, 'tmaskpac', 1, npiglo, npjglo)
+           DO jj=1,npjglo
+              dzonal_heat_pac(jj) = SUM( dtrph(:,jj)*zmask(:,jj) )
+              dzonal_salt_pac(jj) = SUM( dtrps(:,jj)*zmask(:,jj) )
+           END DO
 
-        ! Austral
-        dzonal_heat_aus = 0.d0
-        dzonal_salt_aus = 0.d0
-        !    zmask(:,:)=getvar(cn_fbasins,'tmaskant',1,npiglo,npjglo)
-        !    DO jj=1,npjglo
-        !       dzonal_heat_aus(jj)= SUM( dtrph(:,jj)*zmask(:,jj))
-        !       dzonal_salt_aus(jj)= SUM( dtrps(:,jj)*zmask(:,jj))
-        !    END DO
-
-        !   ! Med
-        dzonal_heat_med = 0.d0
-        dzonal_salt_med = 0.d0
-
-        !    zmask(:,:)=getvar(cn_fbasins,'tmaskmed',1,npiglo,npjglo)
-        !    DO jj=1,npjglo
-        !       dzonal_heat_med(jj)= SUM( dtrph(:,jj)*zmask(:,jj))
-        !       dzonal_salt_med(jj)= SUM( dtrps(:,jj)*zmask(:,jj))
-        !    END DO
-     ENDIF
-      
-     IF (  lzdim  .OR. ( jk == npk ) ) THEN  !output this level
-        IF ( lzdim ) THEN ; ik0 = jk ;  ELSE ;  ik0 = 1  ; ENDIF
-     
-        DO jvar=1,npvar   !  MHT [ and MST ]  (1 or 2 )
-           IF ( jvar == 1 ) THEN
-              ! MHT
-              ivar=1
-              dmtrp(:) = dzonal_heat_glo(:)/1.d15                            ! GLO
-              WHERE ( dmtrp == 0 ) dmtrp = ppspval
-              ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
-              ivar=ivar+1
-              IF ( nbasins == 5 ) THEN
-                 dmtrp(:) = dzonal_heat_atl(:)/1.d15                         ! ATL
-                 WHERE ( dmtrp == 0 ) dmtrp = ppspval         
-                 ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
-                 ivar=ivar+1
-                 dmtrp(:) = (dzonal_heat_ind(:) + dzonal_heat_pac(:))/1.d15  ! INP
-                 WHERE ( dmtrp == 0 ) dmtrp = ppspval
-                 ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
-                 ivar=ivar+1
-                 dmtrp(:) = dzonal_heat_ind(:)/1.d15                         ! IND
-                 WHERE ( dmtrp == 0 ) dmtrp = ppspval
-                 ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
-                 ivar=ivar+1
-                 dmtrp(:) = dzonal_heat_pac(:)/1.d15                         ! PAC
-                 WHERE ( dmtrp == 0 ) dmtrp = ppspval
-                 ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
-                 ivar=ivar+1
-                 ! now inp0
-                 dmtrp(:) = ( dzonal_heat_glo(:) - dzonal_heat_atl(:) )/1.d15 ! INP0
-                 WHERE ( dmtrp == 0 ) dmtrp = ppspval
-                 ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
-                 ivar=ivar+1
-              ENDIF
-           ELSE
-              ! MST
-              dmtrp(:) = dzonal_salt_glo(:)/1.d6                              ! GLO
-              WHERE ( dmtrp == 0 ) dmtrp = ppspval
-              ierr=putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
-              ivar=ivar+1
-              IF ( nbasins == 5 ) THEN
-                 dmtrp(:) = dzonal_salt_atl(:)/1.d6                           ! ATL
-                 WHERE ( dmtrp == 0 ) dmtrp = ppspval
-                 ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
-                 ivar=ivar+1
-                 dmtrp(:) = (dzonal_salt_ind(:) + dzonal_salt_pac(:))/1.d6    ! INP
-                 WHERE ( dmtrp == 0 ) dmtrp = ppspval
-                 ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
-                 ivar=ivar+1
-                 dmtrp(:) = dzonal_salt_ind(:)/1.d6                           ! IND
+           ! Indian
+           zmask(:,:) = getvar(cn_fbasins, 'tmaskind', 1, npiglo, npjglo)
+           DO jj=1,npjglo
+              dzonal_heat_ind(jj) = SUM( dtrph(:,jj)*zmask(:,jj) )
+              dzonal_salt_ind(jj) = SUM( dtrps(:,jj)*zmask(:,jj) )
+           END DO
+
+           ! Austral
+           dzonal_heat_aus = 0.d0
+           dzonal_salt_aus = 0.d0
+           !    zmask(:,:)=getvar(cn_fbasins,'tmaskant',1,npiglo,npjglo)
+           !    DO jj=1,npjglo
+           !       dzonal_heat_aus(jj)= SUM( dtrph(:,jj)*zmask(:,jj))
+           !       dzonal_salt_aus(jj)= SUM( dtrps(:,jj)*zmask(:,jj))
+           !    END DO
+
+           !   ! Med
+           dzonal_heat_med = 0.d0
+           dzonal_salt_med = 0.d0
+
+           !    zmask(:,:)=getvar(cn_fbasins,'tmaskmed',1,npiglo,npjglo)
+           !    DO jj=1,npjglo
+           !       dzonal_heat_med(jj)= SUM( dtrph(:,jj)*zmask(:,jj))
+           !       dzonal_salt_med(jj)= SUM( dtrps(:,jj)*zmask(:,jj))
+           !    END DO
+        ENDIF
+
+        IF (  lzdim  .OR. ( jk == npk ) ) THEN  !output this level
+           IF ( lzdim ) THEN ; ik0 = jk ;  ELSE ;  ik0 = 1  ; ENDIF
+
+           DO jvar=1,npvar   !  MHT [ and MST ]  (1 or 2 )
+              IF ( jvar == 1 ) THEN
+                 ! MHT
+                 ivar=1
+                 dmtrp(:) = dzonal_heat_glo(:)/1.d15                            ! GLO
                  WHERE ( dmtrp == 0 ) dmtrp = ppspval
                  ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
                  ivar=ivar+1
-                 dmtrp(:) = dzonal_salt_pac(:)/1.d6                           ! PAC
+                 IF ( nbasins == 5 ) THEN
+                    dmtrp(:) = dzonal_heat_atl(:)/1.d15                         ! ATL
+                    WHERE ( dmtrp == 0 ) dmtrp = ppspval         
+                    ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
+                    ivar=ivar+1
+                    dmtrp(:) = (dzonal_heat_ind(:) + dzonal_heat_pac(:))/1.d15  ! INP
+                    WHERE ( dmtrp == 0 ) dmtrp = ppspval
+                    ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
+                    ivar=ivar+1
+                    dmtrp(:) = dzonal_heat_ind(:)/1.d15                         ! IND
+                    WHERE ( dmtrp == 0 ) dmtrp = ppspval
+                    ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
+                    ivar=ivar+1
+                    dmtrp(:) = dzonal_heat_pac(:)/1.d15                         ! PAC
+                    WHERE ( dmtrp == 0 ) dmtrp = ppspval
+                    ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
+                    ivar=ivar+1
+                    ! now inp0
+                    dmtrp(:) = ( dzonal_heat_glo(:) - dzonal_heat_atl(:) )/1.d15 ! INP0
+                    WHERE ( dmtrp == 0 ) dmtrp = ppspval
+                    ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
+                    ivar=ivar+1
+                 ENDIF
+              ELSE
+                 ! MST
+                 dmtrp(:) = dzonal_salt_glo(:)/1.d6                              ! GLO
                  WHERE ( dmtrp == 0 ) dmtrp = ppspval
                  ierr=putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
                  ivar=ivar+1
-                 ! now inp0
-                 dmtrp(:) = ( dzonal_salt_glo(:) - dzonal_salt_atl(:) )/1.d6  ! INP0  
-                 WHERE ( dmtrp == 0 ) dmtrp = ppspval
-                 ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
-                 ivar=ivar+1
+                 IF ( nbasins == 5 ) THEN
+                    dmtrp(:) = dzonal_salt_atl(:)/1.d6                           ! ATL
+                    WHERE ( dmtrp == 0 ) dmtrp = ppspval
+                    ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
+                    ivar=ivar+1
+                    dmtrp(:) = (dzonal_salt_ind(:) + dzonal_salt_pac(:))/1.d6    ! INP
+                    WHERE ( dmtrp == 0 ) dmtrp = ppspval
+                    ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
+                    ivar=ivar+1
+                    dmtrp(:) = dzonal_salt_ind(:)/1.d6                           ! IND
+                    WHERE ( dmtrp == 0 ) dmtrp = ppspval
+                    ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
+                    ivar=ivar+1
+                    dmtrp(:) = dzonal_salt_pac(:)/1.d6                           ! PAC
+                    WHERE ( dmtrp == 0 ) dmtrp = ppspval
+                    ierr=putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
+                    ivar=ivar+1
+                    ! now inp0
+                    dmtrp(:) = ( dzonal_salt_glo(:) - dzonal_salt_atl(:) )/1.d6  ! INP0  
+                    WHERE ( dmtrp == 0 ) dmtrp = ppspval
+                    ierr = putvar(ncout, id_varout(ivar), REAL(dmtrp), ik0, 1, npjglo, ktime=jt)
+                    ivar=ivar+1
+                 ENDIF
               ENDIF
-           ENDIF
-        END DO
+           END DO
 
-     ENDIF   ! end loop on check for ouptut
-  END DO  ! loop to next level
+        ENDIF   ! end loop on check for ouptut
+     END DO  ! loop to next level
 
 
      WRITE(numouth,*)'! Zonal heat transport (integrated alon I-model coordinate) (in Pw)'
diff --git a/cdfmht_gsop.f90 b/src/cdfmht_gsop.f90
similarity index 100%
rename from cdfmht_gsop.f90
rename to src/cdfmht_gsop.f90
diff --git a/cdfmkmask.f90 b/src/cdfmkmask.f90
similarity index 97%
rename from cdfmkmask.f90
rename to src/cdfmkmask.f90
index 897b622..d9dd962 100644
--- a/cdfmkmask.f90
+++ b/src/cdfmkmask.f90
@@ -30,6 +30,7 @@ PROGRAM cdfmkmask
    INTEGER(KIND=4)                           :: ierr                     ! working integer
    INTEGER(KIND=4)                           :: narg, iargc, ijarg       ! 
    INTEGER(KIND=4)                           :: npiglo, npjglo, npk, nt  ! size of the domain
+   INTEGER(KIND=4)                           :: npkk                     ! handle case without vertical dim
    INTEGER(KIND=4)                           :: iimin, iimax             ! limit in i
    INTEGER(KIND=4)                           :: ijmin, ijmax             ! limit in j
    INTEGER(KIND=4)                           :: ncout                    ! ncid of output file
@@ -68,7 +69,8 @@ PROGRAM cdfmkmask
       PRINT *,' usage : cdfmkmask T-file [-zoom lonmin lonmax latmin latmax] ...'
       PRINT *,'                   ... [-zoomij iimin iimax ijmin ijmax] ...'
       PRINT *,'                   ... [-zoombat bathymin bathymax]  ...'
-      PRINT *,'                   ... [-o OUT-file ]'
+      PRINT *,'                   ... [-zoomvar varname varmin varmax]  ...'
+      PRINT *,'                   ... [-time ] [-o OUT-file ]'
       PRINT *,'      '
       PRINT *,'     PURPOSE :'
       PRINT *,'       Build a mask file from vosaline array read from the input file.' 
@@ -204,7 +206,13 @@ PROGRAM cdfmkmask
    END IF
 
 
-   ipk(1:4)                       = npk
+   IF ( npk == 0 ) THEN
+     npkk = 1
+   ELSE
+     npkk = npk
+   ENDIF
+    ipk(1:4)                      = npkk
+
    stypvar(1)%cname               = 'tmask'
    stypvar(2)%cname               = 'umask'
    stypvar(3)%cname               = 'vmask'
@@ -265,7 +273,7 @@ PROGRAM cdfmkmask
    !! Now compute the mask 
    DO jt=1, nt
       IF (MOD(jt,10)==0) PRINT *,jt,'/',nt,' ...'
-      DO jk=1, npk
+      DO jk=1, npkk
          ! tmask
          IF ( lmbathy ) THEN
             tmask(:,:) = 1.
diff --git a/src/cdfmltmask.f90 b/src/cdfmltmask.f90
new file mode 100644
index 0000000..d93bd49
--- /dev/null
+++ b/src/cdfmltmask.f90
@@ -0,0 +1,280 @@
+PROGRAM cdfmltmask
+  !!======================================================================
+  !!                     ***  PROGRAM  cdfmltmask  ***
+  !!=====================================================================
+  !!  ** Purpose : multiplication of file by a mask (0,1)
+  !!
+  !! History : 2.1  : 06/2007  : M. Juza      : Original code
+  !!         : 2.1  : 06/2007  : P. Mathiot   : add forcing capabilities
+  !!           3.0  : 01/2011  : J.M. Molines : Doctor norm + Lic.
+  !!           3.0  : 06/2013  : J.M. Molines : add multi variable capability
+  !!           3.0  : 11/2016  : J.M. Molines : use keys for arguments
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id$
+  !! Copyright (c) 2011, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)                             :: jk, jt, jvar       ! dummy loop index
+  INTEGER(KIND=4)                             :: ierr               ! error status
+  INTEGER(KIND=4)                             :: narg, iargc, ijarg ! command line 
+  INTEGER(KIND=4)                             :: npiglo, npjglo     ! size of the domain
+  INTEGER(KIND=4)                             :: npk, npt           ! size of the domain
+  INTEGER(KIND=4)                             :: npkmask            ! vertical levels in mask file
+  INTEGER(KIND=4)                             :: nvar=1             ! number of variable to process(default 1)
+  INTEGER(KIND=4), DIMENSION(:), ALLOCATABLE  :: nvpk               ! vertical levels in working variable
+
+  REAL(KIND=4)                                :: zspval             ! missing value attribute
+  REAL(KIND=4)                                :: zspv0              ! missing value in the output file (default 0)
+  REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: zv                 ! cv_in at jk level 
+  REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: zmask              ! mask at jk level 
+  REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: zvmask             ! masked cv_in at jk level
+
+  CHARACTER(LEN=256)                          :: cunits             ! units attribute
+  CHARACTER(LEN=256)                          :: clname             ! long_name attribute
+  CHARACTER(LEN=256)                          :: csname             ! short_name attribute
+  CHARACTER(LEN=256)                          :: cf_in              ! input file name
+  CHARACTER(LEN=256)                          :: cf_out             ! output file name
+  CHARACTER(LEN=256)                          :: cf_msk             ! input mask file name
+  CHARACTER(LEN=256)                          :: cvartype           ! variable position on Cgrid
+  CHARACTER(LEN=256)                          :: cv_dep             ! depth dim name
+  CHARACTER(LEN=256)                          :: cldum              ! dummy string
+  CHARACTER(LEN=20)                           :: cv_msk             ! mask variable name
+  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_in            ! cdf variable names to process
+
+  LOGICAL                                     :: lnc4=.false.       ! use Netcdf4 chunking and deflation
+  LOGICAL                                     :: lout=.false.       ! specified output file name
+  !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  narg = iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage : cdfmltmask -f IN-file -m MSK-file -v IN-var1,var2,...  '
+     PRINT *,'              -p  T| U | V | F | W | P  [-s _Fillvalue] [-nc4] [-o OUT-file]'
+     PRINT *,'              [ -M MSK-var ]'
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'       Multiply IN-var(s) of IN-file by the mask corresponding to the' 
+     PRINT *,'       C-grid point position given by the -p argument.'
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       -f IN-file  : input netcdf file.' 
+     PRINT *,'       -m MSK-file : input netcdf mask file.' 
+     PRINT *,'       -v IN-var1,var2,...   : Comma separated list of variable names to mask.'
+     PRINT *,'       -p T| U | V | F | W | P : C-grid position of IN-var'
+     PRINT *,'                P indicate a polygon mask created by cdfpoly.'
+     PRINT *,'      OPTIONS : '
+     PRINT *,'        -s _FillValue : specify values for masked areas [0 by default ]'
+     PRINT *,'        -nc4 : output file will be chunked and deflated'
+     PRINT *,'        -o OUT-file : name of output file, instead of <IN-file>_masked'
+     PRINT *,'        -M MSK-var : use MSK-var in the MSK-file, instead of the one defined'
+     PRINT *,'               by default according to the -p option. Overrid -p option.'
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'        none, all are given as arguments.'
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : (jvar)'
+     PRINT *,'       The output file is a copy of the input file with only'
+     PRINT *,'       the requested variable masked.'
+     PRINT *,'       netcdf file : IN-file_masked unless specified with -o '
+     PRINT *,'         variables : IN-var (same as input).'
+     STOP
+  ENDIF
+
+  zspv0 = 0.
+  ijarg = 1
+  cv_msk ='none'
+  DO WHILE (ijarg <= narg)
+    CALL getarg (ijarg, cldum ) ; ijarg = ijarg + 1
+    SELECT CASE ( cldum)
+    CASE ( '-f' )
+        CALL getarg(ijarg, cf_in )   ; ijarg = ijarg + 1
+    CASE ( '-m' )
+        CALL getarg(ijarg, cf_msk)   ; ijarg = ijarg + 1
+    CASE ( '-M' )
+        CALL getarg(ijarg, cv_msk)   ; ijarg = ijarg + 1
+    CASE ( '-v' )
+        CALL getarg(ijarg, cldum)    ; ijarg = ijarg + 1
+        CALL ParseVars ( cldum )
+    CASE ( '-p' )
+        CALL getarg(ijarg, cvartype) ; ijarg = ijarg + 1
+    CASE ( '-s' )
+        CALL getarg(ijarg, cldum)    ; ijarg = ijarg + 1 
+        READ(cldum,*) zspv0
+    CASE ( '-nc4' )
+         lnc4 = .false.
+         PRINT *,' Option -nc4 actually ignored, sorry !, proceed ...'
+    CASE ( '-o' )
+        CALL getarg(ijarg, cf_out )  ; ijarg = ijarg + 1 ; lout=.TRUE.
+    CASE DEFAULT
+        PRINT *, TRIM(cldum), ' : unknown option'
+    END SELECT
+  ENDDO
+
+  IF ( chkfile (cf_in) .OR. chkfile(cf_msk) ) STOP ! missing files
+
+  ! append _masked to input file name and copy initial file to new file, which will be modified
+  !  using dd more efficient than cp for big files
+  IF ( .NOT. lout ) THEN
+     cf_out   = TRIM(cf_in)//'_masked'
+  ENDIF
+  CALL system(' dd bs=10000000 if='//TRIM(cf_in)//' of='//TRIM(cf_out) )
+  cf_in = cf_out
+
+  PRINT *,' Working on copy : ', TRIM(cf_out)
+
+  npiglo = getdim (cf_in,cn_x)
+  npjglo = getdim (cf_in,cn_y)
+  npk    = getdim (cf_in,cn_z, cdtrue=cv_dep, kstatus=ierr)
+
+  IF (ierr /= 0 ) THEN
+     npk   = getdim (cf_in, 'z', cdtrue=cv_dep, kstatus=ierr)
+     IF (ierr /= 0 ) THEN
+       npk   = getdim (cf_in, 'sigma', cdtrue=cv_dep, kstatus=ierr)
+        IF ( ierr /= 0 ) THEN
+          npk = getdim (cf_in, 'nav_lev', cdtrue=cv_dep, kstatus=ierr)
+            IF ( ierr /= 0 ) THEN
+              PRINT *,' assume file with no depth'
+              npk=0
+            ENDIF
+        ENDIF
+     ENDIF
+  ENDIF
+
+  npkmask = getdim (cf_msk, cn_z, cdtrue=cv_dep, kstatus=ierr)
+  IF (ierr /= 0 ) THEN
+     npkmask  = getdim (cf_msk, 'z', cdtrue=cv_dep, kstatus=ierr)
+       IF ( ierr /= 0 ) THEN
+            npkmask = getdim (cf_msk, 'nav_lev', cdtrue=cv_dep, kstatus=ierr)
+            IF ( ierr /= 0 ) THEN
+              PRINT *,' assume file with no depth'
+              npkmask=0
+            ENDIF
+       ENDIF
+  ENDIF
+
+  npt   = getdim (cf_in, cn_t    )
+  ALLOCATE( nvpk(nvar) )
+
+  DO jvar = 1, nvar
+     nvpk(jvar)  = getvdim(cf_in, cv_in(jvar))
+     IF (nvpk(jvar) == 2 ) nvpk(jvar) = 1
+     IF (nvpk(jvar) == 3 ) nvpk(jvar) = npk
+  END DO
+
+  PRINT *, 'npiglo = ', npiglo
+  PRINT *, 'npjglo = ', npjglo
+  PRINT *, 'npk    = ', npk
+  PRINT *, 'npt    = ', npt
+  PRINT *, 'npkmask= ', npkmask
+
+  DO jvar = 1, nvar
+    PRINT *, 'nvpk(',TRIM(cv_in(jvar)),')   = ', nvpk(jvar)
+  END DO
+
+  IF (npk==0) npk=1
+
+  ! Allocate arrays
+  ALLOCATE( zmask(npiglo,npjglo) )
+  ALLOCATE( zv   (npiglo,npjglo) )
+  ALLOCATE(zvmask(npiglo,npjglo) )
+
+  IF ( cv_msk == 'none' ) THEN  ! means cv_msk was not defined by -M option
+  SELECT CASE (TRIM(cvartype))
+  CASE ( 'T' )
+     cv_msk='tmask'
+  CASE ( 'U' )
+     cv_msk='umask'
+  CASE ( 'V' )
+     cv_msk='vmask'
+  CASE ( 'F' )
+     cv_msk='fmask'
+  CASE ( 'W' )
+     cv_msk='tmask'
+  CASE ( 'P' )   ! for polymask 
+     cv_msk='polymask'
+  CASE DEFAULT
+     PRINT *, 'this type of variable is not known :', TRIM(cvartype)
+     STOP
+  END SELECT
+  ENDIF
+
+  IF ( npkmask <= 1 ) THEN 
+        zmask(:,:) = getvar(cf_msk, cv_msk, 1, npiglo, npjglo)
+  ENDIF
+
+  DO jt = 1, npt
+     IF (MOD(jt,100)==0) PRINT *, jt,'/', npt
+     DO jvar = 1, nvar  ! loop on variables
+        DO jk = 1, nvpk(jvar)
+        PRINT *,' Processing level ', jk,' variable ',TRIM(cv_in(jvar))
+        IF ( npkmask > 1 ) THEN
+        ! Read mask
+          zmask(:,:) = getvar(cf_msk, cv_msk, jk, npiglo, npjglo)
+        ENDIF
+          ! Read cv_in
+          zv(:,:) = getvar(cf_in, cv_in(jvar), jk, npiglo, npjglo, ktime=jt)
+          ! Multiplication of cv_in by mask at level jk
+!         zvmask = zv * zmask
+          WHERE ( zmask == 0 ) 
+           zvmask = zspv0
+          ELSEWHERE
+           zvmask = zv
+          ENDWHERE
+          ! Writing  on the copy of original file                 
+          ierr = putvar(cf_out, cv_in(jvar), jk, npiglo, npjglo, 1, 1, ktime=jt, ptab=zvmask)
+        END DO
+     END DO
+  END DO
+
+  ! set missing value attribute for cv_in as 0.
+  DO jvar = 1, nvar 
+     ierr = getvaratt (cf_in, cv_in(jvar), cunits, zspval, clname, csname)
+     IF ( csname == "" ) csname=TRIM( cv_in(jvar) )
+!    ierr = cvaratt   (cf_out, cv_in(jvar), cunits, zspv0,  clname, csname)
+  END DO
+
+CONTAINS
+   SUBROUTINE ParseVars (cdum)
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE ParseVars  ***
+      !!
+      !! ** Purpose :  Decode variables names to be used
+      !!
+      !! ** Method  :  look for , in the argument string and set the number of
+      !!         variable (nvaro), allocate cv_fix array and fill it with the
+      !!         decoded  names.
+      !!
+      !!----------------------------------------------------------------------
+      CHARACTER(LEN=*), INTENT(in) :: cdum
+
+      CHARACTER(LEN=80), DIMENSION(100) :: cl_dum  ! 100 is arbitrary
+      INTEGER  :: ji
+      INTEGER  :: inchar,  i1=1
+      !!----------------------------------------------------------------------
+
+      inchar= LEN(TRIM(cdum))
+      ! scan the input string and look for ',' as separator
+      DO ji=1,inchar
+         IF ( cdum(ji:ji) == ',' ) THEN
+            cl_dum(nvar) = cdum(i1:ji-1)
+            i1=ji+1
+            nvar=nvar+1
+         ENDIF
+      ENDDO
+
+      ! last name of the list does not have a ','
+      cl_dum(nvar) = cdum(i1:inchar)
+
+      ALLOCATE ( cv_in(nvar) )
+      DO ji=1, nvar
+         cv_in(ji) = cl_dum(ji)
+      ENDDO
+   END SUBROUTINE ParseVars
+
+END PROGRAM cdfmltmask 
diff --git a/cdfmoc.f90 b/src/cdfmoc.f90
similarity index 97%
rename from cdfmoc.f90
rename to src/cdfmoc.f90
index 75d3e74..13b37ed 100644
--- a/cdfmoc.f90
+++ b/src/cdfmoc.f90
@@ -21,7 +21,7 @@ PROGRAM cdfmoc
   !!                : 09/2007  : G. Smith      : MOC decomposition
   !!                : 01/2008  : A. Lecointre  : MOC decomposition adaptation 
   !!           3.0  : 03/2011  : J.M. Molines  : Merge all MOC prog, Doctor norm + Lic.
-  !!                : 10/2012  : M.A. Balmaseda: it adds basin INP0=GLOBAL-ATL, different from INP.            : Avoid 3d variables in e3v
+  !!                : 10/2012  : M.A. Balmaseda: it adds basin INP0=GLOBAL-ATL, different from INP.
   !!         
   !!
   !! References :  For MOC decomposition : Lee & Marotzke (1998), 
@@ -121,7 +121,8 @@ PROGRAM cdfmoc
 
   narg= iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfmoc  V_file [-full] [-decomp ] [T_file] [S_file] [U_file] [-rapid] '
+     PRINT *,' usage : cdfmoc  V_file [-full] [-decomp ] [T_file] [S_file] [U_file] ...'
+     PRINT *,'                [-o OUT-file] [-rapid] '
      PRINT *,'     PURPOSE :'
      PRINT *,'       Computes the MOC for oceanic sub basins as described '
      PRINT *,'       in ',TRIM(cn_fbasins)
@@ -130,7 +131,7 @@ PROGRAM cdfmoc
      PRINT *,'       V_file : file with meridional velocity component (mandatory).'
      PRINT *,'       T_file : file with temperature and salinity'
      PRINT *,'               (required only for -decomp option).'
-     PRINT *,'       S_file  (required only for -rapid option --might be the same as T_file-- ).'
+     PRINT *,'       S_file  (required only for -rapid option, might be the same as T_file).'
      PRINT *,'       U_file  (required only for -rapid option).'
      PRINT *,'      '
      PRINT *,'     OPTIONS :'
@@ -146,6 +147,7 @@ PROGRAM cdfmoc
      PRINT *,'                   - 1100-3000m  : upper-NADW recirculation'
      PRINT *,'                   - 3000-5000m  : lower-NADW recirculation'
      PRINT *,'                   - 5000-bottom : AABW recirculation'
+     PRINT *,'       [-o OUT-file ] : specify output file instead of ',TRIM(cf_moc)
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'       Files ',TRIM(cn_fhgr),' ', TRIM(cn_fhgr),' and ', TRIM(cn_fmsk)
@@ -164,9 +166,10 @@ PROGRAM cdfmoc
      PRINT *,'       If decomposition is required , ( option -decomp ) add 3 additional'
      PRINT *,'       variables per basin with suffixes _sh, _bt, _ag.'
      PRINT *,'      '
-     PRINT *,'       If option -rapid in use the output file (rapid_moc.nc)is degenerated '
+     PRINT *,'       If option -rapid is used the output file (rapid_moc.nc) is degenerated'
      PRINT *,'       into 6 scalar values : tr_gs, tr_THERM, tr_AIW, tr_UNADW, tr_LNADW, '
-     PRINT *,'       tr_BW and a vertical profile of the AMOC at 26.5N, as computed traditionally.'
+     PRINT *,'       tr_BW and a vertical profile of the AMOC at 26.5N, as computed'
+     PRINT *,'       traditionally.'
      PRINT *,'       Additional variables are also computed following CLIVAR-GODAE '
      PRINT *,'       reanalysis intercomparison project recommendations. '
      STOP
@@ -184,6 +187,8 @@ PROGRAM cdfmoc
         ldec    = .TRUE.
      CASE ('-rapid') 
         lrap    = .TRUE.
+     CASE ('-o') 
+        CALL getarg (ijarg, cf_moc) ; ijarg=ijarg+1
      CASE DEFAULT
         ii=ii+1
         SELECT CASE (ii)
@@ -239,171 +244,6 @@ PROGRAM cdfmoc
      nvarout=nbasinso       ! total
   ENDIF
 
-  ALLOCATE ( stypvar(nvarout), ipk(nvarout), id_varout(nvarout) )
-
-  ! define new variables for output 
-  !    all variables
-  stypvar%cunits            = 'Sverdrup'
-  stypvar%rmissing_value    = 99999.
-  stypvar%valid_min         = -1000.
-  stypvar%valid_max         =  1000.
-  stypvar%scale_factor      = 1.
-  stypvar%add_offset        = 0.
-  stypvar%savelog10         = 0.
-  stypvar%conline_operation = 'N/A'
-  stypvar%caxis             = 'TZY'
-  ipk(:) = npk  ! All variables are vertical slices 1 x npjglo x npk
-
-  ii=1 ; ibasin=1
-  PRINT *, 'Variable ',ii,' is zomsfglo'
-  npglo=ibasin  ; ibasin = ibasin + 1 
-  stypvar(ii)%cname          = TRIM(cn_zomsfglo)
-  stypvar(ii)%clong_name     = 'Meridional_Overt.Cell_Global'
-  stypvar(ii)%cshort_name    = TRIM(cn_zomsfglo)
-  ii=ii+1
-
-  IF ( ldec ) THEN
-     PRINT *, 'Variable ',ii,' is zomsfglo_sh'
-     stypvar(ii)%cname       = TRIM(cn_zomsfglo)//'_sh'
-     stypvar(ii)%clong_name  = 'GeoShear_Merid_StreamFunction'
-     stypvar(ii)%cshort_name = TRIM(cn_zomsfglo)//'_sh'
-     ii= ii+1
-     PRINT *, 'Variable ',ii,' is zomsfglo_bt'
-     stypvar(ii)%cname       = TRIM(cn_zomsfglo)//'_bt'
-     stypvar(ii)%clong_name  = 'Barotropic_Merid_StreamFunction'
-     stypvar(ii)%cshort_name = TRIM(cn_zomsfglo)//'_bt'
-     ii= ii+1
-     PRINT *, 'Variable ',ii,' is zomsfglo_ag'
-     stypvar(ii)%cname       = TRIM(cn_zomsfglo)//'_ag'
-     stypvar(ii)%clong_name  = 'Ageostoph_Merid_StreamFunction'
-     stypvar(ii)%cshort_name = TRIM(cn_zomsfglo)//'_ag'
-     ii= ii+1
-  ENDIF
-
-  IF (lbas) THEN
-     npatl=ibasin  ; ibasin = ibasin + 1
-     PRINT *, 'Variable ',ii,' is zomsfatl'
-     stypvar(ii)%cname       = TRIM(cn_zomsfatl)
-     stypvar(ii)%clong_name  = 'Meridional_Overt.Cell_Atlantic'
-     stypvar(ii)%cshort_name = TRIM(cn_zomsfatl)
-     ii= ii+1
-     IF ( ldec ) THEN 
-        PRINT *, 'Variable ',ii,' is zomsfatl_sh'
-        stypvar(ii)%cname       = TRIM(cn_zomsfatl)//'_sh'
-        stypvar(ii)%clong_name  = 'GeoShear_Merid_StreamFunction_Atlantic'
-        stypvar(ii)%cshort_name = TRIM(cn_zomsfatl)//'_sh'
-        ii= ii+1
-        PRINT *, 'Variable ',ii,' is zomsfatl_bt'
-        stypvar(ii)%cname       = TRIM(cn_zomsfatl)//'_bt'
-        stypvar(ii)%clong_name  = 'Barotropic_Merid_StreamFunction_Atlantic'
-        stypvar(ii)%cshort_name = TRIM(cn_zomsfatl)//'_bt'
-        ii= ii+1
-        PRINT *, 'Variable ',ii,' is zomsfatl_ag'
-        stypvar(ii)%cname       = TRIM(cn_zomsfatl)//'_ag'
-        stypvar(ii)%clong_name  = 'Ageostroph_Merid_StreamFunction_Atlantic'
-        stypvar(ii)%cshort_name = TRIM(cn_zomsfatl)//'_ag'
-        ii= ii+1
-     ENDIF
-
-     npinp=ibasin  ; ibasin = ibasin + 1
-     PRINT *, 'Variable ',ii,' is zomsfinp'
-     stypvar(ii)%cname       = TRIM(cn_zomsfinp)
-     stypvar(ii)%clong_name  = 'Meridional_Overt.Cell_IndoPacif'
-     stypvar(ii)%cshort_name = TRIM(cn_zomsfinp)
-     ii= ii+1
-
-     IF ( ldec ) THEN
-        PRINT *, 'Variable ',ii,' is zomsfinp_sh'
-        stypvar(ii)%cname       = TRIM(cn_zomsfinp)//'_sh'
-        stypvar(ii)%clong_name  = 'GeoShear_Merid_StreamFunction_IndoPacif'
-        stypvar(ii)%cshort_name = TRIM(cn_zomsfinp)//'_sh'
-        ii= ii+1
-        PRINT *, 'Variable ',ii,' is zomsfinp_bt'
-        stypvar(ii)%cname       = TRIM(cn_zomsfinp)//'_bt'
-        stypvar(ii)%clong_name  = 'Barotropic_Merid_StreamFunction_IndoPacif'
-        stypvar(ii)%cshort_name = TRIM(cn_zomsfinp)//'_bt'
-        ii= ii+1
-        PRINT *, 'Variable ',ii,' is zomsfinp_ag'
-        stypvar(ii)%cname       = TRIM(cn_zomsfinp)//'_ag'
-        stypvar(ii)%clong_name  = 'Ageostroph_Merid_StreamFunction_IndoPacif'
-        stypvar(ii)%cshort_name = TRIM(cn_zomsfinp)//'_ag'
-        ii= ii+1
-     ENDIF
-
-     npind=ibasin  ; ibasin = ibasin + 1
-     PRINT *, 'Variable ',ii,' is zomsfind'
-     stypvar(ii)%cname       = TRIM(cn_zomsfind)
-     stypvar(ii)%clong_name  = 'Meridional_Overt.Cell_Indian'
-     stypvar(ii)%cshort_name = TRIM(cn_zomsfind)
-     ii= ii+1
-
-     IF ( ldec ) THEN
-        PRINT *, 'Variable ',ii,' is zomsfind_sh'
-        stypvar(ii)%cname       = TRIM(cn_zomsfind)//'_sh'
-        stypvar(ii)%clong_name  = 'GeoShear_Merid_StreamFunction_Indian'
-        stypvar(ii)%cshort_name = TRIM(cn_zomsfind)//'_sh'
-        ii= ii+1
-        PRINT *, 'Variable ',ii,' is zomsfind_bt'
-        stypvar(ii)%cname       = TRIM(cn_zomsfind)//'_bt'
-        stypvar(ii)%clong_name  = 'Barotropic_Merid_StreamFunction_Indian'
-        stypvar(ii)%cshort_name = TRIM(cn_zomsfind)//'_bt'
-        ii= ii+1
-        PRINT *, 'Variable ',ii,' is zomsfind_ag'
-        stypvar(ii)%cname       = TRIM(cn_zomsfind)//'_ag'
-        stypvar(ii)%clong_name  = 'Ageostroph_Merid_StreamFunction_Indian'
-        stypvar(ii)%cshort_name = TRIM(cn_zomsfind)//'_ag'
-        ii= ii+1
-     ENDIF
-
-     nppac=ibasin  ; ibasin = ibasin + 1
-     PRINT *, 'Variable ',ii,' is zomsfpac'
-     stypvar(ii)%cname       = TRIM(cn_zomsfpac)
-     stypvar(ii)%clong_name  = 'Meridional_Overt.Cell_pacif'
-     stypvar(ii)%cshort_name = TRIM(cn_zomsfpac)
-     ii= ii+1
-
-     IF ( ldec ) THEN
-        PRINT *, 'Variable ',ii,' is zomsfpac_sh'
-        stypvar(ii)%cname       = TRIM(cn_zomsfpac)//'_sh'
-        stypvar(ii)%clong_name  = 'GeoShear_Merid_StreamFunction_Pacif'
-        stypvar(ii)%cshort_name = TRIM(cn_zomsfpac)//'_sh'
-        ii= ii+1
-        PRINT *, 'Variable ',ii,' is zomsfpac_bt'
-        stypvar(ii)%cname       = TRIM(cn_zomsfpac)//'_bt'
-        stypvar(ii)%clong_name  = 'Barotropic_Merid_StreamFunction_Pacif'
-        stypvar(ii)%cshort_name = TRIM(cn_zomsfpac)//'_bt'
-        ii= ii+1
-        PRINT *, 'Variable ',ii,' is zomsfpac_ag'
-        stypvar(ii)%cname       = TRIM(cn_zomsfpac)//'_ag'
-        stypvar(ii)%clong_name  = 'Ageostroph_Merid_StreamFunction_Pacif'
-        stypvar(ii)%cshort_name = TRIM(cn_zomsfpac)//'_ag'
-        ii=ii+1
-     ENDIF
-
-     npinp0=ibasin  ; ibasin = ibasin + 1
-     PRINT *, 'Variable ',ii,' is zomsfinp0'
-     stypvar(ii)%cname       = TRIM(cn_zomsfinp0)
-     stypvar(ii)%clong_name  = 'Meridional_Overt.Cell_IndPac0'
-     stypvar(ii)%cshort_name = TRIM(cn_zomsfinp0)
-     ii= ii+1
-
-     IF ( ldec ) THEN
-        PRINT *, 'Variable ',ii,' is zomsfinp0_sh'
-        stypvar(ii)%cname       = TRIM(cn_zomsfinp0)//'_sh'
-        stypvar(ii)%clong_name  = 'GeoShear_Merid_StreamFunction_IndPac0'
-        stypvar(ii)%cshort_name = TRIM(cn_zomsfinp0)//'_sh'
-        ii= ii+1
-        PRINT *, 'Variable ',ii,' is zomsfinp0_bt'
-        stypvar(ii)%cname       = TRIM(cn_zomsfinp0)//'_bt'
-        stypvar(ii)%clong_name  = 'Barotropic_Merid_StreamFunction_IndPac0'
-        stypvar(ii)%cshort_name = TRIM(cn_zomsfinp0)//'_bt'
-        ii= ii+1
-        PRINT *, 'Variable ',ii,' is zomsfinp0_ag'
-        stypvar(ii)%cname       = TRIM(cn_zomsfinp0)//'_ag'
-        stypvar(ii)%clong_name  = 'Ageostroph_Merid_StreamFunction_IndPac0'
-        stypvar(ii)%cshort_name = TRIM(cn_zomsfinp0)//'_ag'
-     ENDIF
-  ENDIF
 
   ! Allocate arrays
   ALLOCATE ( ibmask(nbasins, npiglo, npjglo) )
@@ -435,25 +275,23 @@ PROGRAM cdfmoc
   gphiv(:,:) = getvar  (cn_fhgr, cn_gphiv, 1, npiglo,npjglo)
   gdepw(:)   = getvare3(cn_fzgr, cn_gdepw, npk             )
   gdepw(:)   = -1.* gdepw(:)
-  DO jk= 1, npk
-     ! save e3v masked with vmask as 3d array
-     e3v(:,:,jk) = get_e3v(jk)
-  END DO
+
 
   IF ( ldec  ) gdept(:) = getvare3(cn_fzgr, cn_gdept, npk             )
   IF ( ldec  ) e1u(:,:) = getvar  (cn_fhgr, cn_ve1u,  1, npiglo,npjglo)
   IF ( lfull ) e31d(:)  = getvare3(cn_fzgr, cn_ve3t, npk)
 
+  DO jk= 1, npk
+     ! save e3v masked with vmask as 3d array
+     e3v(:,:,jk) = get_e3v(jk)
+  END DO
+
   iloc=MAXLOC(gphiv)
   rdumlat(1,:) = gphiv(iloc(1),:)
   rdumlon(:,:) = 0.   ! set the dummy longitude to 0
 
-  ! create output fileset
-  ncout = create      ( cf_moc,  'none',    1, npjglo, npk, cdep=cn_vdepthw )
-  ierr  = createvar   ( ncout,   stypvar,   nvarout,   ipk, id_varout, cdglobal=TRIM(cglobal)           )
-  ierr  = putheadervar( ncout,   cf_vfil,   1, npjglo, npk, pnavlon=rdumlon, pnavlat=rdumlat, pdep=gdepw)
-  tim   = getvar1d    ( cf_vfil, cn_vtimec, npt                    )
-  ierr  = putvar1d    ( ncout,   tim,       npt, 'T')
+  ALLOCATE ( stypvar(nvarout), ipk(nvarout), id_varout(nvarout) )
+  CALL CreateOutput
 
   ! 1 : global ; 2 : Atlantic ; 3 : Indo-Pacif ; 4 : Indian ; 5 : Pacif
   ibmask(npglo,:,:) = getvar(cn_fmsk,   'vmask', 1, npiglo, npjglo)
@@ -478,6 +316,7 @@ PROGRAM cdfmoc
         DO jk = 1, npk-1
            ! Get velocities v at jk, time = jt
            zv(:,:)= getvar(cf_vfil, cn_vomecrty,  jk, npiglo, npjglo, ktime=jt)
+!          print *, jk, MAXVAL(zv)
 
            IF ( ldec ) THEN
               ! compute barotropic component when requested
@@ -487,21 +326,27 @@ PROGRAM cdfmoc
            ENDIF
 
            ! integrates 'zonally' (along i-coordinate)
-           DO ji=1,npiglo
+           DO jbasin = 1, nbasins
+              !$OMP PARALLEL DO SCHEDULE(RUNTIME)
+              DO jj=1,npjglo
+                 DO ji=1,npiglo
               ! For all basins 
-              DO jbasin = 1, nbasins
-                 DO jj=1,npjglo
                     dmoc(jbasin,jj,jk)=dmoc(jbasin,jj,jk) -  &
                          &             e1v(ji,jj)*e3v(ji,jj,jk)* ibmask(jbasin,ji,jj)*zv(ji,jj)*1.d0
                  ENDDO
               END DO
+              !$OMP END PARALLEL DO
            END DO
         END DO
 
         ! integrates vertically from bottom to surface
+        !$OMP PARALLEL DO SCHEDULE(RUNTIME)
+        DO jj = 1, npjglo
         DO jk = npk-1, 1, -1
-           dmoc(:,:,jk)    = dmoc(:,:,jk+1)    + dmoc(:,:,jk)/1.d6
+           dmoc(:,jj,jk)    = dmoc(:,jj,jk+1)    + dmoc(:,jj,jk)/1.d6
         END DO
+        ENDDO
+        !$OMP END PARALLEL DO
 
         IF ( ldec ) THEN
            !--------------------------------------------------
@@ -659,6 +504,7 @@ PROGRAM cdfmoc
            ENDIF
         END DO
 
+        IF ( lbas ) THEN
         jbasin=nbasinso
            DO jk = 1, npk
               ierr = putvar (ncout, id_varout(ijvar), REAL(dmoc(npglo,:,jk)-dmoc(npatl,:,jk)), jk, 1, npjglo, ktime=jt)
@@ -681,7 +527,7 @@ PROGRAM cdfmoc
               END DO
               ijvar = ijvar + 1 
            ENDIF
-
+        ENDIF
      ENDDO  ! time loop
 
      ierr = closeout(ncout)
@@ -823,7 +669,7 @@ PROGRAM cdfmoc
 
        ! prepare output dataset: 7 variables
        ! add 12 new variables for CLIVAR GSOP-GODAE intercomparison
-       cf_moc = 'rapid_moc.nc'
+       cf_moc = 'rapid_'//TRIM(cf_moc)
        nvarout =  33
        ALLOCATE ( stypvar(nvarout), ipk(nvarout), id_varout(nvarout) )
        stypvar%cunits            = 'Sverdrup'
@@ -1310,4 +1156,186 @@ PROGRAM cdfmoc
 
      END SUBROUTINE rapid_amoc
 
+     SUBROUTINE CreateOutput
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE CreateOutput  ***
+    !!
+    !! ** Purpose :  Prepare netcdf files for output 
+    !!
+    !! ** Method  :  use global module variables 
+    !!
+    !!----------------------------------------------------------------------
+  ! define new variables for output 
+  !    all variables
+  stypvar%cunits            = 'Sverdrup'
+  stypvar%rmissing_value    = 99999.
+  stypvar%valid_min         = -1000.
+  stypvar%valid_max         =  1000.
+  stypvar%scale_factor      = 1.
+  stypvar%add_offset        = 0.
+  stypvar%savelog10         = 0.
+  stypvar%conline_operation = 'N/A'
+  stypvar%caxis             = 'TZY'
+  ipk(:) = npk  ! All variables are vertical slices 1 x npjglo x npk
+
+  ii=1 ; ibasin=1
+  PRINT *, 'Variable ',ii,' is zomsfglo'
+  npglo=ibasin  ; ibasin = ibasin + 1 
+  stypvar(ii)%cname          = TRIM(cn_zomsfglo)
+  stypvar(ii)%clong_name     = 'Meridional_Overt.Cell_Global'
+  stypvar(ii)%cshort_name    = TRIM(cn_zomsfglo)
+  ii=ii+1
+
+  IF ( ldec ) THEN
+     PRINT *, 'Variable ',ii,' is zomsfglo_sh'
+     stypvar(ii)%cname       = TRIM(cn_zomsfglo)//'_sh'
+     stypvar(ii)%clong_name  = 'GeoShear_Merid_StreamFunction'
+     stypvar(ii)%cshort_name = TRIM(cn_zomsfglo)//'_sh'
+     ii= ii+1
+     PRINT *, 'Variable ',ii,' is zomsfglo_bt'
+     stypvar(ii)%cname       = TRIM(cn_zomsfglo)//'_bt'
+     stypvar(ii)%clong_name  = 'Barotropic_Merid_StreamFunction'
+     stypvar(ii)%cshort_name = TRIM(cn_zomsfglo)//'_bt'
+     ii= ii+1
+     PRINT *, 'Variable ',ii,' is zomsfglo_ag'
+     stypvar(ii)%cname       = TRIM(cn_zomsfglo)//'_ag'
+     stypvar(ii)%clong_name  = 'Ageostoph_Merid_StreamFunction'
+     stypvar(ii)%cshort_name = TRIM(cn_zomsfglo)//'_ag'
+     ii= ii+1
+  ENDIF
+
+  IF (lbas) THEN
+     npatl=ibasin  ; ibasin = ibasin + 1
+     PRINT *, 'Variable ',ii,' is zomsfatl'
+     stypvar(ii)%cname       = TRIM(cn_zomsfatl)
+     stypvar(ii)%clong_name  = 'Meridional_Overt.Cell_Atlantic'
+     stypvar(ii)%cshort_name = TRIM(cn_zomsfatl)
+     ii= ii+1
+     IF ( ldec ) THEN 
+        PRINT *, 'Variable ',ii,' is zomsfatl_sh'
+        stypvar(ii)%cname       = TRIM(cn_zomsfatl)//'_sh'
+        stypvar(ii)%clong_name  = 'GeoShear_Merid_StreamFunction_Atlantic'
+        stypvar(ii)%cshort_name = TRIM(cn_zomsfatl)//'_sh'
+        ii= ii+1
+        PRINT *, 'Variable ',ii,' is zomsfatl_bt'
+        stypvar(ii)%cname       = TRIM(cn_zomsfatl)//'_bt'
+        stypvar(ii)%clong_name  = 'Barotropic_Merid_StreamFunction_Atlantic'
+        stypvar(ii)%cshort_name = TRIM(cn_zomsfatl)//'_bt'
+        ii= ii+1
+        PRINT *, 'Variable ',ii,' is zomsfatl_ag'
+        stypvar(ii)%cname       = TRIM(cn_zomsfatl)//'_ag'
+        stypvar(ii)%clong_name  = 'Ageostroph_Merid_StreamFunction_Atlantic'
+        stypvar(ii)%cshort_name = TRIM(cn_zomsfatl)//'_ag'
+        ii= ii+1
+     ENDIF
+
+     npinp=ibasin  ; ibasin = ibasin + 1
+     PRINT *, 'Variable ',ii,' is zomsfinp'
+     stypvar(ii)%cname       = TRIM(cn_zomsfinp)
+     stypvar(ii)%clong_name  = 'Meridional_Overt.Cell_IndoPacif'
+     stypvar(ii)%cshort_name = TRIM(cn_zomsfinp)
+     ii= ii+1
+
+     IF ( ldec ) THEN
+        PRINT *, 'Variable ',ii,' is zomsfinp_sh'
+        stypvar(ii)%cname       = TRIM(cn_zomsfinp)//'_sh'
+        stypvar(ii)%clong_name  = 'GeoShear_Merid_StreamFunction_IndoPacif'
+        stypvar(ii)%cshort_name = TRIM(cn_zomsfinp)//'_sh'
+        ii= ii+1
+        PRINT *, 'Variable ',ii,' is zomsfinp_bt'
+        stypvar(ii)%cname       = TRIM(cn_zomsfinp)//'_bt'
+        stypvar(ii)%clong_name  = 'Barotropic_Merid_StreamFunction_IndoPacif'
+        stypvar(ii)%cshort_name = TRIM(cn_zomsfinp)//'_bt'
+        ii= ii+1
+        PRINT *, 'Variable ',ii,' is zomsfinp_ag'
+        stypvar(ii)%cname       = TRIM(cn_zomsfinp)//'_ag'
+        stypvar(ii)%clong_name  = 'Ageostroph_Merid_StreamFunction_IndoPacif'
+        stypvar(ii)%cshort_name = TRIM(cn_zomsfinp)//'_ag'
+        ii= ii+1
+     ENDIF
+
+     npind=ibasin  ; ibasin = ibasin + 1
+     PRINT *, 'Variable ',ii,' is zomsfind'
+     stypvar(ii)%cname       = TRIM(cn_zomsfind)
+     stypvar(ii)%clong_name  = 'Meridional_Overt.Cell_Indian'
+     stypvar(ii)%cshort_name = TRIM(cn_zomsfind)
+     ii= ii+1
+
+     IF ( ldec ) THEN
+        PRINT *, 'Variable ',ii,' is zomsfind_sh'
+        stypvar(ii)%cname       = TRIM(cn_zomsfind)//'_sh'
+        stypvar(ii)%clong_name  = 'GeoShear_Merid_StreamFunction_Indian'
+        stypvar(ii)%cshort_name = TRIM(cn_zomsfind)//'_sh'
+        ii= ii+1
+        PRINT *, 'Variable ',ii,' is zomsfind_bt'
+        stypvar(ii)%cname       = TRIM(cn_zomsfind)//'_bt'
+        stypvar(ii)%clong_name  = 'Barotropic_Merid_StreamFunction_Indian'
+        stypvar(ii)%cshort_name = TRIM(cn_zomsfind)//'_bt'
+        ii= ii+1
+        PRINT *, 'Variable ',ii,' is zomsfind_ag'
+        stypvar(ii)%cname       = TRIM(cn_zomsfind)//'_ag'
+        stypvar(ii)%clong_name  = 'Ageostroph_Merid_StreamFunction_Indian'
+        stypvar(ii)%cshort_name = TRIM(cn_zomsfind)//'_ag'
+        ii= ii+1
+     ENDIF
+
+     nppac=ibasin  ; ibasin = ibasin + 1
+     PRINT *, 'Variable ',ii,' is zomsfpac'
+     stypvar(ii)%cname       = TRIM(cn_zomsfpac)
+     stypvar(ii)%clong_name  = 'Meridional_Overt.Cell_pacif'
+     stypvar(ii)%cshort_name = TRIM(cn_zomsfpac)
+     ii= ii+1
+
+     IF ( ldec ) THEN
+        PRINT *, 'Variable ',ii,' is zomsfpac_sh'
+        stypvar(ii)%cname       = TRIM(cn_zomsfpac)//'_sh'
+        stypvar(ii)%clong_name  = 'GeoShear_Merid_StreamFunction_Pacif'
+        stypvar(ii)%cshort_name = TRIM(cn_zomsfpac)//'_sh'
+        ii= ii+1
+        PRINT *, 'Variable ',ii,' is zomsfpac_bt'
+        stypvar(ii)%cname       = TRIM(cn_zomsfpac)//'_bt'
+        stypvar(ii)%clong_name  = 'Barotropic_Merid_StreamFunction_Pacif'
+        stypvar(ii)%cshort_name = TRIM(cn_zomsfpac)//'_bt'
+        ii= ii+1
+        PRINT *, 'Variable ',ii,' is zomsfpac_ag'
+        stypvar(ii)%cname       = TRIM(cn_zomsfpac)//'_ag'
+        stypvar(ii)%clong_name  = 'Ageostroph_Merid_StreamFunction_Pacif'
+        stypvar(ii)%cshort_name = TRIM(cn_zomsfpac)//'_ag'
+        ii=ii+1
+     ENDIF
+
+     npinp0=ibasin  ; ibasin = ibasin + 1
+     PRINT *, 'Variable ',ii,' is zomsfinp0'
+     stypvar(ii)%cname       = TRIM(cn_zomsfinp0)
+     stypvar(ii)%clong_name  = 'Meridional_Overt.Cell_IndPac0'
+     stypvar(ii)%cshort_name = TRIM(cn_zomsfinp0)
+     ii= ii+1
+
+     IF ( ldec ) THEN
+        PRINT *, 'Variable ',ii,' is zomsfinp0_sh'
+        stypvar(ii)%cname       = TRIM(cn_zomsfinp0)//'_sh'
+        stypvar(ii)%clong_name  = 'GeoShear_Merid_StreamFunction_IndPac0'
+        stypvar(ii)%cshort_name = TRIM(cn_zomsfinp0)//'_sh'
+        ii= ii+1
+        PRINT *, 'Variable ',ii,' is zomsfinp0_bt'
+        stypvar(ii)%cname       = TRIM(cn_zomsfinp0)//'_bt'
+        stypvar(ii)%clong_name  = 'Barotropic_Merid_StreamFunction_IndPac0'
+        stypvar(ii)%cshort_name = TRIM(cn_zomsfinp0)//'_bt'
+        ii= ii+1
+        PRINT *, 'Variable ',ii,' is zomsfinp0_ag'
+        stypvar(ii)%cname       = TRIM(cn_zomsfinp0)//'_ag'
+        stypvar(ii)%clong_name  = 'Ageostroph_Merid_StreamFunction_IndPac0'
+        stypvar(ii)%cshort_name = TRIM(cn_zomsfinp0)//'_ag'
+     ENDIF
+  ENDIF
+
+  ! create output fileset
+  ncout = create      ( cf_moc,  'none',    1, npjglo, npk, cdep=cn_vdepthw )
+  ierr  = createvar   ( ncout,   stypvar,   nvarout,   ipk, id_varout, cdglobal=TRIM(cglobal)           )
+  ierr  = putheadervar( ncout,   cf_vfil,   1, npjglo, npk, pnavlon=rdumlon, pnavlat=rdumlat, pdep=gdepw)
+  tim   = getvar1d    ( cf_vfil, cn_vtimec, npt                    )
+  ierr  = putvar1d    ( ncout,   tim,       npt, 'T')
+
+     END SUBROUTINE CreateOutput
+
    END PROGRAM cdfmoc
diff --git a/cdfmocsig.f90 b/src/cdfmocsig.f90
similarity index 61%
rename from cdfmocsig.f90
rename to src/cdfmocsig.f90
index a875f08..bd12558 100644
--- a/cdfmocsig.f90
+++ b/src/cdfmocsig.f90
@@ -21,6 +21,8 @@ PROGRAM cdfmocsig
   !!                : 03/2010  : C. Dufour     : Choice of depth reference
   !!                                             improvements 
   !!           3.0  : 04/2011  : J.M. Molines  : Doctor norm + Lic.
+  !!           3.0  : 06/2013  : J.M. Molines  : add neutral density
+  !!           3.0  : 06/2013  : J.M. Molines  : add bin mean depth calculation and OpenMp directives
   !!----------------------------------------------------------------------
   USE cdfio
   USE eos
@@ -45,12 +47,15 @@ PROGRAM cdfmocsig
   INTEGER(KIND=4)                                 :: ierr                 ! working integer
   INTEGER(KIND=4)                                 :: narg, iargc, iarg    ! command line  browsing 
   INTEGER(KIND=4)                                 :: ijarg, ii            !  "             "
+  INTEGER(KIND=4)                                 :: ib                   ! current bin number
+  INTEGER(KIND=4)                                 :: ij1, ij2             ! current J index
   INTEGER(KIND=4)                                 :: npiglo,npjglo        ! size of the domain
   INTEGER(KIND=4)                                 :: npk, npt             ! size of the domain
   INTEGER(KIND=4)                                 :: ncout                ! ncid of output file
+  INTEGER(KIND=4)                                 :: nvaro                ! number of output variables
   INTEGER(KIND=4), DIMENSION(2)                   :: iloc                 ! working array
   INTEGER(KIND=4), DIMENSION(:),      ALLOCATABLE :: ipk, id_varout       ! output variable levels and id
-  INTEGER(KIND=4), DIMENSION (:,:),   ALLOCATABLE :: ibin                 ! remaping density in bin number
+  INTEGER(KIND=4), DIMENSION(:,:),    ALLOCATABLE :: ibin                 ! remaping density in bin number
 
   REAL(KIND=4), DIMENSION (:,:),      ALLOCATABLE :: e1v, gphiv           ! horizontal metrics, latitude
   REAL(KIND=4), DIMENSION (:,:),      ALLOCATABLE :: zt, zs               ! temperature, salinity
@@ -59,16 +64,23 @@ PROGRAM cdfmocsig
   REAL(KIND=4), DIMENSION (:,:),      ALLOCATABLE :: rdumlon              ! dummy longitude = 0.
   REAL(KIND=4), DIMENSION (:,:),      ALLOCATABLE :: rdumlat              ! latitude for i = north pole
   REAL(KIND=4), DIMENSION (:,:),      ALLOCATABLE :: zttmp                ! arrays to call sigmai and mask it
+  REAL(KIND=4), DIMENSION (:,:),      ALLOCATABLE :: zarea                ! product e1v * e3v
   REAL(KIND=4), DIMENSION (:),        ALLOCATABLE :: sigma                ! density coordinate 
   REAL(KIND=4), DIMENSION (:),        ALLOCATABLE :: e31d                 ! vertical level (full step)
+  REAL(KIND=4), DIMENSION (:),        ALLOCATABLE :: gdep                 ! depth of T layers ( full step)
   REAL(KIND=4), DIMENSION (:),        ALLOCATABLE :: tim                  ! time counter
+  REAL(KIND=4), PARAMETER                         :: rp_spval=99999.      !
   REAL(KIND=4)                                    :: pref=0.              ! depth reference for pot. density 
   REAL(KIND=4)                                    :: sigmin               ! minimum density for bining
   REAL(KIND=4)                                    :: sigstp               ! density step for bining
 
   REAL(KIND=8), DIMENSION(:,:,:),     ALLOCATABLE :: dmoc                 ! nbasins x npjglo x npk
+  REAL(KIND=8), DIMENSION(:,:,:),     ALLOCATABLE :: depi                 ! Zonal mean of depths of isopycnal
+  REAL(KIND=8), DIMENSION(:,:,:),     ALLOCATABLE :: wdep                 ! count array
   REAL(KIND=8), DIMENSION(:,:),       ALLOCATABLE :: dens                 ! density
   REAL(KIND=8), DIMENSION(:,:),       ALLOCATABLE :: dmoc_tmp             ! temporary transport array
+  REAL(KIND=8), DIMENSION(:,:),       ALLOCATABLE :: depi_tmp             ! temporary cumulated depth array
+  REAL(KIND=8), DIMENSION(:,:),       ALLOCATABLE :: wdep_tmp             ! temporary count array
 
   CHARACTER(LEN=256)                              :: cf_vfil              ! meridional velocity file
   CHARACTER(LEN=256)                              :: cf_tfil              ! temperature/salinity file
@@ -79,7 +91,9 @@ PROGRAM cdfmocsig
   TYPE(variable), DIMENSION(:), ALLOCATABLE       :: stypvar              ! output var properties
 
   LOGICAL, DIMENSION(3)                           :: lbin                 ! flag for bin specifications
+  LOGICAL                                         :: lntr                 ! flag for neutral density
   LOGICAL                                         :: lbas   = .FALSE.     ! flag for basins file
+  LOGICAL                                         :: lisodep= .FALSE.     ! flag for isopycnal zonal mean
   LOGICAL                                         :: lprint = .FALSE.     ! flag for extra print
   LOGICAL                                         :: leiv   = .FALSE.     ! flag for Eddy Induced Velocity (GM)
   LOGICAL                                         :: lfull  = .FALSE.     ! flag for full step
@@ -90,7 +104,7 @@ PROGRAM cdfmocsig
   narg= iargc()
   IF ( narg == 0 ) THEN
      PRINT *,' usage : cdfmocsig  V_file T_file depth_ref [-eiv] [-full]  ... '
-     PRINT *,'         ...  [-sigmin sigmin] [-sigstp sigstp] [-nbins nbins] [-v] '
+     PRINT *,'         ...  [-sigmin sigmin] [-sigstp sigstp] [-nbins nbins] [-isodep] [-v]'
      PRINT *,'     PURPOSE : '
      PRINT *,'       Computes the MOC in density-latitude coordinates. The global value'
      PRINT *,'       is always computed. Values for oceanic sub-basins are calculated'
@@ -109,6 +123,8 @@ PROGRAM cdfmocsig
      PRINT *,'               minimum density, number of density bins and width of density'
      PRINT *,'               bins are provided. For other reference depth, you must use'
      PRINT *,'               -sigmin, -sigstp and -nbins options (see below).'
+     PRINT *,'               Keyword ''ntr'' can also be used in place of depth_ref in '
+     PRINT *,'               order to use neutral density (no default bin defined so far).'
      PRINT *,'      '
      PRINT *,'     OPTIONS :'
      PRINT *,'       [-eiv ] : takes into account VEIV Meridional eddy induced velocity'
@@ -118,6 +134,7 @@ PROGRAM cdfmocsig
      PRINT *,'       [ -sigmin ] : Specify minimum of density for bining'
      PRINT *,'       [ -sigstp ] : Specify density step for bining'
      PRINT *,'       [ -nbins ]  : Specify the number of density bins you want'
+     PRINT *,'       [ -isodep]  : Compute the zonal mean of isopycnal depths used for mocsig'
      PRINT *,'       [ -v  ]     : Verbose option for more info during execution'
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
@@ -133,6 +150,8 @@ PROGRAM cdfmocsig
      PRINT *,'       variables ',TRIM( cn_zomsfpac),' : Pacific Ocean alone'
      PRINT *,'       If file ',TRIM(cn_fbasins),' is not present, ',TRIM(cn_fmsk),' file'
      PRINT *,'       is used and only ',TRIM( cn_zomsfglo),' is produced.'
+     PRINT *,'       If option -isodep is used, each MOC variable is complemented by a iso'
+     PRINT *,'       variable, giving the zonal mean of ispycnal depth (e.g.',TRIM(cn_zoisoglo),').'
      STOP
   ENDIF
 
@@ -156,6 +175,8 @@ PROGRAM cdfmocsig
      CASE ('-sigstp')
         CALL getarg (ijarg, cldum) ; ijarg=ijarg+1 ; READ(cldum,*) sigstp
         lbin(3) = .FALSE.
+     CASE ('-isodep')
+        lisodep = .TRUE.
      CASE ('-v')
         lprint = .TRUE.
      CASE DEFAULT
@@ -163,7 +184,11 @@ PROGRAM cdfmocsig
         SELECT CASE (ii)
         CASE ( 1 ) ; cf_vfil = cldum
         CASE ( 2 ) ; cf_tfil = cldum
-        CASE ( 3 ) ; READ(cldum,*) pref
+        CASE ( 3 ) 
+             SELECT CASE ( cldum )
+             CASE ( 'ntr', 'NTR', 'Ntr' ) ; lntr = .TRUE.
+             CASE DEFAULT                 ; READ(cldum,*) pref
+             END SELECT
         CASE DEFAULT
            STOP 'ERROR : Too many arguments ...'
         END SELECT
@@ -203,31 +228,48 @@ PROGRAM cdfmocsig
      nbasins = 1
   ENDIF
 
-  ALLOCATE ( stypvar(nbasins), ipk(nbasins), id_varout(nbasins) )
+  IF ( lisodep ) THEN
+     nvaro = 2 * nbasins
+  ELSE
+     nvaro =     nbasins
+  ENDIF
+
+  ALLOCATE ( stypvar(nvaro), ipk(nvaro), id_varout(nvaro) )
 
   IF ( lchk )  THEN  ! use default bins definition according to pref 
      ! Define density parameters
-     SELECT CASE ( INT(pref) )
-     CASE ( 0 )
-        nbins  = 52
-        sigmin  = 23.
-        sigstp = 0.1
-     CASE ( 1000 )
-        nbins  = 88
-        sigmin  = 24.
-        sigstp = 0.1
-     CASE ( 2000)
-        nbins  = 158
-        sigmin  = 30.
-        sigstp = 0.05
-     CASE DEFAULT
-        PRINT *,' This value of depth_ref (',pref,') is not implemented as standard'
-        PRINT *,' You must use the -sigmin, -sigstp and -nbins options to precise'
-        PRINT *,' the density bining you want to use.'
-        STOP
-     END SELECT
+     IF ( lntr) THEN   ! to be confirmed ( note that sigmantr returns values > 1000 kg/m3)
+         nbins  = 52
+         sigmin = 1023.
+         sigstp = 0.1
+     ELSE
+       SELECT CASE ( INT(pref) )
+       CASE ( 0 )
+          nbins  = 52
+          sigmin = 23.
+          sigstp = 0.1
+       CASE ( 1000 )
+          nbins  = 88
+          sigmin = 24.
+          sigstp = 0.1
+       CASE ( 2000)
+          nbins  = 158
+          sigmin = 30.
+          sigstp = 0.05
+       CASE DEFAULT
+          PRINT *,' This value of depth_ref (',pref,') is not implemented as standard'
+          PRINT *,' You must use the -sigmin, -sigstp and -nbins options to precise'
+          PRINT *,' the density bining you want to use.'
+          STOP
+       END SELECT
+     ENDIF
+  ENDIF
+
+  IF (lntr ) THEN
+     PRINT '(a,f6.1,a)',           '  For Neutral density MOC'
+  ELSE
+     PRINT '(a,f6.1,a)',           '  For reference depth ', pref, ' m, '
   ENDIF
-  PRINT '(a,f6.1,a)',           '  For reference depth ', pref, ' m, '
   PRINT '(a,f5.2,a,f5.2,a,i3)', '  You are using -sigmin ', sigmin,' -sigstp ', sigstp,' -nbins ', nbins
 
   ALLOCATE ( sigma(nbins) )  
@@ -238,79 +280,44 @@ PROGRAM cdfmocsig
   ENDDO
   IF (lprint) PRINT *, ' min density:',sigma(1), ' max density:', sigma(nbins)
 
-  !global   ; Atlantic  ; Indo-Pacif ; Indian  ; Pacif
-  npglo= 1  ; npatl=2   ;  npinp=3   ; npind=4 ; nppac=5
-
-  ! Common to all variables :
-  stypvar%cunits            = 'Sverdrup'
-  stypvar%rmissing_value    = 99999.
-  stypvar%valid_min         = -1000.
-  stypvar%valid_max         =  1000.
-  stypvar%scale_factor      = 1.
-  stypvar%add_offset        = 0.
-  stypvar%savelog10         = 0.
-  stypvar%conline_operation = 'N/A'
-  stypvar%caxis             = 'TZY'
-
-  ipk(:) = npk  
-
-  ! Global basin
-  stypvar(npglo)%cname       = cn_zomsfglo
-  stypvar(npglo)%clong_name  = 'Meridional_Overt.Cell_Global'
-  stypvar(npglo)%cshort_name = cn_zomsfglo
-
-  IF (lbas) THEN
-     stypvar(npatl)%cname       = cn_zomsfatl
-     stypvar(npatl)%clong_name  = 'Meridional_Overt.Cell_Atlantic'
-     stypvar(npatl)%cshort_name = cn_zomsfatl
-
-     stypvar(npinp)%cname       = cn_zomsfinp
-     stypvar(npinp)%clong_name  = 'Meridional_Overt.Cell_IndoPacif'
-     stypvar(npinp)%cshort_name = cn_zomsfinp
-
-     stypvar(npind)%cname       = cn_zomsfind
-     stypvar(npind)%clong_name  = 'Meridional_Overt.Cell_Indian'
-     stypvar(npind)%cshort_name = cn_zomsfind
-
-     stypvar(nppac)%cname       = cn_zomsfpac
-     stypvar(nppac)%clong_name  = 'Meridional_Overt.Cell_pacif'
-     stypvar(nppac)%cshort_name = cn_zomsfpac
-  ENDIF
-
   ! Allocate arrays
   ALLOCATE ( ibmask(nbasins,npiglo,npjglo) )
-  ALLOCATE ( zv (npiglo,npjglo), zt(npiglo,npjglo), zs(npiglo,npjglo))
+  ALLOCATE ( zv (npiglo,npjglo), zt(npiglo,npjglo), zs(npiglo,npjglo), zarea(npiglo, npjglo) )
   ALLOCATE ( e3v(npiglo,npjglo) )
   ALLOCATE ( ibin(npiglo, npjglo) )
   ALLOCATE ( e1v(npiglo,npjglo), gphiv(npiglo,npjglo) )
-  ALLOCATE ( dmoc(nbasins, npjglo, nbins) )
-  ALLOCATE ( dmoc_tmp(nbins,npiglo) )
+  ALLOCATE ( dmoc(nvaro, nbins, npjglo ) )
   ALLOCATE ( rdumlon(1,npjglo) , rdumlat(1,npjglo))
   ALLOCATE ( dens(npiglo,npjglo))
   ALLOCATE ( itmask(npiglo,npjglo), zttmp(npiglo,npjglo))
   ALLOCATE ( tim(npt), e31d(npk)  )
 
-  IF ( leiv ) THEN
-     ALLOCATE ( zveiv (npiglo,npjglo))
-  END IF
+  IF ( lisodep) THEN 
+                ALLOCATE ( depi(nvaro, nbins, npjglo), gdep(npk))
+                ALLOCATE ( wdep(nvaro, nbins, npjglo)           )
+  ENDIF
+  IF ( leiv   ) ALLOCATE ( zveiv (npiglo,npjglo))
 
   e1v(:,:)   = getvar(cn_fhgr,   cn_ve1v,  1, npiglo, npjglo) 
-  gphiv(:,:) = getvar(cn_fhgr,   cn_gphiv, 1, npiglo, npjglo)
 
-  IF ( lfull ) e31d(:)  = getvare3(cn_fzgr, cn_ve3t, npk)
+  IF ( lfull  ) e31d(:) = getvare3(cn_fzgr, cn_ve3t,  npk )
+  IF ( lisodep) gdep(:) = -getvare3(cn_fzgr, cn_gdept, npk )  ! take negative value
+                                                              ! to be compliant with zonal mean
 
-  iloc         = MAXLOC(gphiv)
-  rdumlat(1,:) = gphiv(iloc(1),:)
+  IF ( npjglo > 1 ) THEN 
+     gphiv(:,:)   = getvar(cn_fhgr, cn_gphiv, 1, npiglo, npjglo)
+     iloc         = MAXLOC(gphiv)
+     rdumlat(1,:) = gphiv(iloc(1),:)
+  ELSE
+     rdumlat(1,:) = 0.
+  ENDIF
   rdumlon(:,:) = 0.               ! set the dummy longitude to 0
 
   ! create output fileset
-! ncout = create      (cf_moc, cf_vfil, 1,       npjglo, nbins,  cdep='sigma')
-  ncout = create      (cf_moc, 'none', 1,       npjglo, nbins,  cdep='sigma')
-  ierr  = createvar   (ncout,  stypvar, nbasins, ipk ,id_varout, cdglobal=cglobal)
-  ierr  = putheadervar(ncout,  cf_vfil, 1,       npjglo, nbins,  pnavlon=rdumlon, pnavlat=rdumlat, pdep=sigma)
+  !global   ; Atlantic  ; Indo-Pacif ; Indian  ; Pacif
+  npglo= 1  ; npatl=2   ;  npinp=3   ; npind=4 ; nppac=5
 
-  tim  = getvar1d(cf_vfil, cn_vtimec, npt     )
-  ierr = putvar1d(ncout,   tim,       npt, 'T')
+  CALL CreateOutputFiles
 
   ! reading the masks
   ibmask(npglo,:,:) = getvar(cn_fmsk, 'vmask', 1, npiglo, npjglo)
@@ -329,69 +336,126 @@ PROGRAM cdfmocsig
 
   DO jt=1, npt
      ! initialize moc to 0
-     dmoc(:,:,:) = 0.d0
+     dmoc(:,:,:) = 0.d0 
+     IF ( lisodep ) THEN 
+       depi(:,:,:) = 0.d0 ; wdep(:,:,:) = 0.d0
+     ENDIF
 
      DO jk=1,npk-1
         !               for testing purposes only loop from 2 to 400
         IF (lprint) PRINT *,' working at depth ',jk
         ! Get velocities v at jj
-        zv(:,:) = getvar(cf_vfil, cn_vomecrty, jk, npiglo, npjglo)
+        zv(:,:) = getvar(cf_vfil, cn_vomecrty, jk, npiglo, npjglo, ktime = jt)
         IF ( leiv ) THEN
-           zveiv(:,:) = getvar(cf_vfil, cn_vomeeivv, jk, npiglo,npjglo)
+           zveiv(:,:) = getvar(cf_vfil, cn_vomeeivv, jk, npiglo,npjglo, ktime = jt)
            zv(:,:)    = zv(:,:) + zveiv(:,:)
         END IF
-        zt(:,:) = getvar(cf_tfil, cn_votemper, jk, npiglo, npjglo)
-        zs(:,:) = getvar(cf_tfil, cn_vosaline, jk, npiglo, npjglo)
+        ! JMM remark : should be more correct to use t and s a V point ?
+        zt(:,:) = getvar(cf_tfil, cn_votemper, jk, npiglo, npjglo, ktime = jt)
+        zs(:,:) = getvar(cf_tfil, cn_vosaline, jk, npiglo, npjglo, ktime = jt)
 
         ! get e3v at latitude jj
         IF ( lfull ) THEN
-          e3v(:,:) = e31d(jk)
+           e3v(:,:) = e31d(jk)
         ELSE
-          e3v(:,:) = getvar(cn_fzgr, 'e3v_ps', jk, npiglo, npjglo, ldiom=.TRUE.)
+           e3v(:,:) = getvar(cn_fzgr, 'e3v_ps', jk, npiglo, npjglo, ldiom=.TRUE.)
         ENDIF
+        zarea(:,:) = e1v(:,:) * e3v(:,:)
         !
         !  finds density 
         itmask =  1
         WHERE ( zs == 0 ) itmask = 0
-        dens  = sigmai(zt, zs, pref, npiglo, npjglo)
+        IF ( lntr ) THEN
+           dens  = sigmantr(zt, zs,     npiglo, npjglo)
+        ELSE
+           dens  = sigmai(zt, zs, pref, npiglo, npjglo)
+        ENDIF
+
         zttmp = dens* itmask ! convert to single precision 
         ! find bin numbers
         ibin(:,:) = INT( (zttmp-sigmin)/sigstp )
         ibin(:,:) = MAX( ibin(:,:), 1    )
         ibin(:,:) = MIN( ibin(:,:), nbins)
 
-        DO jj=2,npjglo-1
-           dmoc_tmp = 0
+        IF ( npjglo > 1 ) THEN
+           ij1 = 2 ; ij2 = npjglo-1
+        ELSE
+           ij1 = 1 ; ij2 = 1 ! input file has only one j ( case of extracted broken lines) 
+        ENDIF
+!$OMP PARALLEL  PRIVATE(dmoc_tmp,depi_tmp,wdep_tmp, ib)
+                       ALLOCATE ( dmoc_tmp(nbins,npiglo) )
+        IF ( lisodep ) ALLOCATE ( depi_tmp(nbins,npiglo) )
+        IF ( lisodep ) ALLOCATE ( wdep_tmp(nbins,npiglo) )
+        IF ( lprint ) PRINT *, ' Entering main J loop '
+        !$OMP DO SCHEDULE(RUNTIME)
+        DO jj= ij1, ij2
+           dmoc_tmp = 0.d0 
            !  converts transport in "k" to transport in "sigma"
            !  indirect adresssing - do it once and not for each basin!
            DO ji=2,npiglo-1
-              dmoc_tmp(ibin(ji,jj),ji)=dmoc_tmp(ibin(ji,jj),ji) - e1v(ji,jj)*e3v(ji,jj)*zv(ji,jj)
+              ib = ibin(ji,jj)
+              dmoc_tmp(ib,ji) = dmoc_tmp(ib,ji) - zv(ji,jj)*zarea(ji,jj)
            END DO
+
+           IF ( lisodep ) THEN
+              depi_tmp = 0.d0 ; wdep_tmp = 0.d0 ! wdep(:,:) = 0
+              DO ji=2,npiglo-1
+                 ib = ibin(ji,jj)
+                 depi_tmp(ib,ji) = depi_tmp(ib,ji) + gdep(jk) * itmask(ji,jj)*zarea(ji,jj)
+                 wdep_tmp(ib,ji) = wdep_tmp(ib,ji) +            itmask(ji,jj)*zarea(ji,jj)  ! total weight
+              END DO
+           ENDIF
            ! integrates 'zonally' (along i-coordinate) 
            ! add to dmoc the contributions from level jk  at all densities jbin
-           DO jbin =1,nbins  
-              DO ji=2,npiglo-1
-                 DO jbasin= 1, nbasins
+           
+!          IF ( lprint ) PRINT *, ' Entering main bin loop ', jj,ij2
+           DO jbasin= 1, nbasins
+              DO jbin =1,nbins  
+                 DO ji=2,npiglo-1
                     ! For all basins 
-                    dmoc(jbasin,jj,jbin)=dmoc(jbasin,jj,jbin ) + dmoc_tmp(jbin,ji) * ibmask(jbasin,ji,jj)
+                    dmoc(jbasin,jbin,jj)=dmoc(jbasin,jbin,jj) + dmoc_tmp(jbin,ji) * ibmask(jbasin,ji,jj)
                  ENDDO
               END DO
            END DO
-           !               end of loop on latitude for filling dmoc
-        END DO
-        !  end of loop on depths for calculating transports     
-     END DO
+
+           IF ( lisodep) THEN
+           DO jbasin= 1, nbasins
+              DO jbin =1,nbins
+                 DO ji=2,npiglo-1
+                       depi(jbasin,jbin,jj)=depi(jbasin,jbin,jj) + depi_tmp(jbin,ji) * ibmask(jbasin,ji,jj)
+                       wdep(jbasin,jbin,jj)=wdep(jbasin,jbin,jj) + wdep_tmp(jbin,ji) * ibmask(jbasin,ji,jj)
+                 ENDDO
+              END DO
+           END DO
+
+           ENDIF
+        END DO  ! end of loop on latitude for filling dmoc
+        !$OMP END DO
+                       DEALLOCATE (dmoc_tmp)
+        IF ( lisodep ) DEALLOCATE (depi_tmp)
+        IF ( lisodep ) DEALLOCATE (wdep_tmp)
+!$OMP END PARALLEL
+     END DO     ! end of loop on depths for calculating transports     
+
+     IF ( lisodep ) THEN
+        WHERE ( wdep(:,:,:) /= 0.d0 ) 
+         depi(:,:,:) = depi(:,:,:) / wdep (:,:,:)
+        ELSEWHERE
+         depi(:,:,:) = rp_spval
+        END WHERE
+     ENDIF
 
      ! integrates across bins from highest to lowest density
-     dmoc(:,:,nbins) = dmoc(:,:,nbins)/1.e6
-     DO jk=nbins-1, 1, -1
-        dmoc(:,:,jk) = dmoc(:,:,jk+1) + dmoc(:,:,jk)/1.e6
+     dmoc(:,nbins,:) = dmoc(:,nbins,:)/1.e6
+     DO jbin=nbins-1, 1, -1
+        dmoc(:,jbin,:) = dmoc(:,jbin+1,:) + dmoc(:,jbin,:)/1.e6
      END DO  ! loop to next bin
 
      ! netcdf output  
      DO jbasin = 1, nbasins
-        DO jk = 1, nbins
-           ierr = putvar (ncout, id_varout(jbasin), REAL(dmoc(jbasin,:,jk)), jk, 1, npjglo)
+        DO jbin = 1, nbins
+                         ierr = putvar (ncout, id_varout(jbasin        ), REAL(dmoc(jbasin,jbin,:)), jbin, 1, npjglo, ktime = jt)
+           IF (lisodep ) ierr = putvar (ncout, id_varout(jbasin+nbasins), REAL(depi(jbasin,jbin,:)), jbin, 1, npjglo, ktime = jt)
         END DO
      END DO
 
@@ -399,5 +463,100 @@ PROGRAM cdfmocsig
 
   ierr = closeout(ncout)
 
+  CONTAINS
+  SUBROUTINE CreateOutputFiles
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE CreateOutputFiles ***
+    !!
+    !! ** Purpose :  Initialize and create output files 
+    !!
+    !! ** Method  :  Check the number of sub_basin, and options 
+    !!
+    !!----------------------------------------------------------------------
+
+  ! Common to all variables :
+  stypvar%cunits            = 'Sverdrup'
+  stypvar%rmissing_value    = rp_spval
+  stypvar%valid_min         = -1000.
+  stypvar%valid_max         =  1000.
+  stypvar%scale_factor      = 1.
+  stypvar%add_offset        = 0.
+  stypvar%savelog10         = 0.
+  stypvar%conline_operation = 'N/A'
+  stypvar%caxis             = 'TZY'
+
+  ipk(:) = nbins
+
+  ! Global basin
+  stypvar(npglo)%cname       = cn_zomsfglo
+  stypvar(npglo)%clong_name  = 'Meridional_Overt.Cell_Global'
+  stypvar(npglo)%cshort_name = cn_zomsfglo
+
+  IF (lbas) THEN
+     stypvar(npatl)%cname       = cn_zomsfatl
+     stypvar(npatl)%clong_name  = 'Meridional_Overt.Cell_Atlantic'
+     stypvar(npatl)%cshort_name = cn_zomsfatl
+
+     stypvar(npinp)%cname       = cn_zomsfinp
+     stypvar(npinp)%clong_name  = 'Meridional_Overt.Cell_IndoPacif'
+     stypvar(npinp)%cshort_name = cn_zomsfinp
+
+     stypvar(npind)%cname       = cn_zomsfind
+     stypvar(npind)%clong_name  = 'Meridional_Overt.Cell_Indian'
+     stypvar(npind)%cshort_name = cn_zomsfind
+
+     stypvar(nppac)%cname       = cn_zomsfpac
+     stypvar(nppac)%clong_name  = 'Meridional_Overt.Cell_pacif'
+     stypvar(nppac)%cshort_name = cn_zomsfpac
+  ENDIF
+
+  IF ( lisodep ) THEN
+     ! Global basin
+     stypvar(npglo+nbasins)%cunits      = 'm'
+     stypvar(npglo+nbasins)%cname       = cn_zoisoglo
+     stypvar(npglo+nbasins)%clong_name  = 'Zonal_mean_isopycnal_depth_Global'
+     stypvar(npglo+nbasins)%cshort_name = cn_zoisoglo
+     stypvar(npglo+nbasins)%valid_min   = 0.
+     stypvar(npglo+nbasins)%valid_max   = 8000.
+     IF ( lbas ) THEN
+        stypvar(npatl+nbasins)%cunits      = 'm'
+        stypvar(npatl+nbasins)%cname       = cn_zoisoatl
+        stypvar(npatl+nbasins)%clong_name  = 'Zonal_mean_isopycnal_depth_Atlantic'
+        stypvar(npatl+nbasins)%cshort_name = cn_zoisoatl
+        stypvar(npatl+nbasins)%valid_min   = 0.
+        stypvar(npatl+nbasins)%valid_max   = 8000.
+
+        stypvar(npinp+nbasins)%cunits      = 'm'
+        stypvar(npinp+nbasins)%cname       = cn_zoisoinp
+        stypvar(npinp+nbasins)%clong_name  = 'Zonal_mean_isopycnal_depth_IndoPacif'
+        stypvar(npinp+nbasins)%cshort_name = cn_zoisoinp
+        stypvar(npinp+nbasins)%valid_min   = 0.
+        stypvar(npinp+nbasins)%valid_max   = 8000.
+
+        stypvar(npind+nbasins)%cunits      = 'm'
+        stypvar(npind+nbasins)%cname       = cn_zoisoind
+        stypvar(npind+nbasins)%clong_name  = 'Zonal_mean_isopycnal_depth_Indian'
+        stypvar(npind+nbasins)%cshort_name = cn_zoisoind
+        stypvar(npind+nbasins)%valid_min   = 0.
+        stypvar(npind+nbasins)%valid_max   = 8000.
+
+        stypvar(nppac+nbasins)%cunits      = 'm'
+        stypvar(nppac+nbasins)%cname       = cn_zoisopac
+        stypvar(nppac+nbasins)%clong_name  = 'Zonal_mean_isopycnal_depth_pacif'
+        stypvar(nppac+nbasins)%cshort_name = cn_zoisopac
+        stypvar(nppac+nbasins)%valid_min   = 0.
+        stypvar(nppac+nbasins)%valid_max   = 8000.
+     ENDIF
+  ENDIF
+
+  ncout = create      (cf_moc, 'none', 1,      npjglo, nbins,  cdep='sigma')
+  ierr  = createvar   (ncout,  stypvar, nvaro, ipk ,id_varout, cdglobal=cglobal)
+  ierr  = putheadervar(ncout,  cf_vfil, 1,     npjglo, nbins,  pnavlon=rdumlon, pnavlat=rdumlat, pdep=sigma)
+
+  tim  = getvar1d(cf_vfil, cn_vtimec, npt     )
+  ierr = putvar1d(ncout,   tim,       npt, 'T')
+
+  END SUBROUTINE CreateOutputFiles
+
 END PROGRAM cdfmocsig
    
diff --git a/cdfmoy.f90 b/src/cdfmoy.f90
similarity index 68%
rename from cdfmoy.f90
rename to src/cdfmoy.f90
index 80d165f..e48493b 100644
--- a/cdfmoy.f90
+++ b/src/cdfmoy.f90
@@ -15,6 +15,7 @@ PROGRAM cdfmoy
   !! History : 2.0  : 11/2004  : J.M. Molines : Original code
   !!         : 2.1  : 06/2007  : P. Mathiot   : Modif for forcing fields
   !!           3.0  : 12/2010  : J.M. Molines : Doctor norm + Lic.
+  !!                  04/2015  : S. Leroux    : add nomissincl option
   !!----------------------------------------------------------------------
   !!----------------------------------------------------------------------
   !!   routines      : description
@@ -32,9 +33,10 @@ PROGRAM cdfmoy
   !!-----------------------------------------------------------------------------
   IMPLICIT NONE
 
-  INTEGER(KIND=4)                               :: jk, jfil           ! dummy loop index
+  INTEGER(KIND=4)                               :: jk, jfil,jdep      ! dummy loop index
   INTEGER(KIND=4)                               :: jvar, jv, jt       ! dummy loop index
   INTEGER(KIND=4)                               :: ierr               ! working integer
+  INTEGER(KIND=4)                               :: idep, idep_max     ! possible depth index, maximum
   INTEGER(KIND=4)                               :: narg, iargc, ijarg ! browsing command line
   INTEGER(KIND=4)                               :: nfil               ! number of files to average
   INTEGER(KIND=4)                               :: npiglo, npjglo     ! size of the domain
@@ -44,14 +46,21 @@ PROGRAM cdfmoy
   INTEGER(KIND=4)                               :: ncout              ! ncid of output files
   INTEGER(KIND=4)                               :: ncout2             ! ncid of output files
   INTEGER(KIND=4)                               :: ncout3             ! ncid of output files
-  INTEGER(KIND=4)                               :: nperio=4           ! ncid of output files
+  INTEGER(KIND=4)                               :: ncout4             ! ncid of output files
+  INTEGER(KIND=4)                               :: nperio=4           ! periodic flag
+  INTEGER(KIND=4)                               :: iwght              ! weight of variable
   INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_var             ! arrays of var id's
   INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: ipk                ! arrays of vertical level for each var
+  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: ipk4               ! arrays of vertical level for min/max
   INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_varout          ! varid's of average vars
   INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_varout2         ! varid's of sqd average vars
   INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_varout3         ! varid's of cub average vars
+  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_varout4         ! varid's of cub average vars
 
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: rmask2d             ![from SL]
   REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: v2d                ! array to read a layer of data
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: rmax               ! array for maximum value
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: rmin               ! array for minimum value
   REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: rmean              ! average
   REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: rmean2             ! squared average
   REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: rmean3             ! cubic average
@@ -64,37 +73,46 @@ PROGRAM cdfmoy
   REAL(KIND=8)                                  :: dtotal_time        ! to compute mean time
 
   CHARACTER(LEN=256)                            :: cf_in              ! input file names
+  CHARACTER(LEN=256)                            :: cf_root='cdfmoy'       ! optional root of output files 
   CHARACTER(LEN=256)                            :: cf_out  = 'cdfmoy.nc'  ! output file for average
   CHARACTER(LEN=256)                            :: cf_out2 = 'cdfmoy2.nc' ! output file for squared average
   CHARACTER(LEN=256)                            :: cf_out3 = 'cdfmoy3.nc' ! output file for squared average
+  CHARACTER(LEN=256)                            :: cf_out4 = 'cdfmoy_minmax.nc'  ! output file for min/max
   CHARACTER(LEN=256)                            :: cv_dep             ! depth dimension name
   CHARACTER(LEN=256)                            :: cldum              ! dummy string argument
   CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cf_list            ! list of input files
   CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_nam             ! array of var name
   CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_nam2            ! array of var2 name for output
   CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_nam3            ! array of var3 name for output
+  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_nam4            ! array of var3 name for output
+  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: clv_dep            ! array of possible depth name (or 3rd dimension)
   
   TYPE (variable), DIMENSION(:),    ALLOCATABLE :: stypvar            ! attributes for average values
   TYPE (variable), DIMENSION(:),    ALLOCATABLE :: stypvar2           ! attributes for square averaged values
   TYPE (variable), DIMENSION(:),    ALLOCATABLE :: stypvar3           ! attributes for cubic averaged values
+  TYPE (variable), DIMENSION(:),    ALLOCATABLE :: stypvar4           ! attributes for min/max
 
   LOGICAL                                       :: lcaltmean          ! mean time computation flag
   LOGICAL                                       :: lspval0 = .false.  ! cdfmoy_chsp flag
   LOGICAL                                       :: lcubic  = .false.  ! 3rd momment computation
   LOGICAL                                       :: lzermean = .false. ! flag for zero-mean process
+  LOGICAL                                       :: lmax    = .false.  ! flag for min/max computation
   LOGICAL                                       :: lchk    = .false.  ! flag for missing files
+  LOGICAL                                       :: lnc4    = .false.  ! flag for netcdf4 output
+  LOGICAL                                       :: lnomissincl =.false.! [from SL] flag for excuding gridpoints where some values are missing
   !!----------------------------------------------------------------------------
   CALL ReadCdfNames()
 
   narg= iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfmoy list_of_model_files [-spval0] [-cub ] [-zeromean]'
+     PRINT *,' usage : cdfmoy list_of_model_files [-spval0] [-cub ] [-zeromean] [-max]'
+     PRINT *,'               [-nomissincl] [-nc4 ] [-o output_file_root ]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
-     PRINT *,'       Compute the time average of a list of files given as arguments.' 
-     PRINT *,'       The program assume that all files in the list are of same'
+     PRINT *,'       Computes the time average of a list of files given as arguments.' 
+     PRINT *,'       The program assumes that all files in the list are of same'
      PRINT *,'       type (shape, variables etc...). '
-     PRINT *,'       For some variables, the program also compute the time average '
+     PRINT *,'       For some variables, the program also computes the time average '
      PRINT *,'       of the squared variables, which is used in other cdftools '
      PRINT *,'       (cdfeke, cdfrmsssh, cdfstdevw, cdfstddevts ... The actual variables'
      PRINT *,'       selected for squared average are :'
@@ -113,14 +131,24 @@ PROGRAM cdfmoy
      PRINT *,'               variables and take care of the input missing_value.'
      PRINT *,'               This option is usefull if missing_values differ from files '
      PRINT *,'               to files; it was formely done by cdfmoy_chsp).'
-     PRINT *,'       [ -cub ] :  use this option if you want to compute third order moment'
+     PRINT *,'       [ -cub ] :  use this option if you want to compute third order moments'
      PRINT *,'               for the eligible variables, which are at present :'
      PRINT '(15x,"- ",a)' , (TRIM(cn_cubvar(jv)), jv=1, nn_cubvar)
      PRINT *,'              This selection can be adapted with the nam_cdf_namelist process.'
      PRINT *,'              (See cdfnamelist -i for details).'
      PRINT *,'       [ -zeromean ] : with this option, the spatial mean value for each '
-     PRINT *,'              time frame is substracted from the original field previous '
-     PRINT *,'              averaging, square averaging and eventually cubic averaging'
+     PRINT *,'              time frame is substracted from the original field before '
+     PRINT *,'              averaging, square averaging and eventually cubic averaging.'
+     PRINT *,'       [-max ] : with this option, a file with the minimum and maximum values'
+     PRINT *,'              of the variables is created.'
+     PRINT *,'       [-nomissincl ] : with this option, the output mean is set to missing' 
+     PRINT *,'              value at any gridpoint where the variable contains a  missing'
+     PRINT *,'              value for at least one timestep. You should combine with option'
+     PRINT *,'              -spval0 if missing values are not 0 in all  the input files.'
+     PRINT *,'       [ -nc4 ] Use netcdf4 output with chunking and deflation level 1'
+     PRINT *,'               This option is effective only if cdftools are compiled with'
+     PRINT *,'               a netcdf library supporting chunking and deflation.'
+     PRINT *,'       [ -o output file root ] Default is ', TRIM(cf_root) 
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'       If -zeromean option is used, need ', TRIM(cn_fhgr),' and ',TRIM(cn_fmsk)
@@ -129,8 +157,10 @@ PROGRAM cdfmoy
      PRINT *,'       netcdf file : ', TRIM(cf_out),' and ',TRIM(cf_out2)
      PRINT *,'       variables : are the same than in the input files. For squared averages' 
      PRINT *,'       _sqd is append to the original variable name.'
-     PRINT *,'       IF -cub option is used, the file ', TRIM(cf_out3),' is also created'
+     PRINT *,'       If -cub option is used, the file ', TRIM(cf_out3),' is also created'
      PRINT *,'       with _cub append to the original variable name.'
+     PRINT *,'       If -max option is used, file ',TRIM(cf_out4),' is also created, with '
+     PRINT *,'       same variable names.'
      PRINT *,'      '
      PRINT *,'     SEE ALSO :'
      PRINT *,'       cdfmoy_weighted, cdfstdev'
@@ -152,11 +182,24 @@ PROGRAM cdfmoy
         lcubic = .true.
      CASE ( '-zeromean' )   ! option to reset spval to 0 in the output files
         lzermean = .true.
+     CASE ( '-max' )   ! option to reset spval to 0 in the output files
+        lmax = .true.
+     CASE ( '-nomissincl' )   ! [from SL] option to mask the output at gridpoints where some values are missing
+        lnomissincl = .true.   ! [from SL]
+     CASE ( '-nc4' )   !  allow chunking and deflation on output
+        lnc4 = .true.
+     CASE ( '-o' )     ! specify root of output files
+        CALL getarg (ijarg, cf_root) ; ijarg = ijarg + 1
+
      CASE DEFAULT         ! then the argument is a file
         nfil          = nfil + 1
         cf_list(nfil) = TRIM(cldum)
      END SELECT
   END DO
+  cf_out=TRIM(cf_root)//'.nc'
+  cf_out2=TRIM(cf_root)//'2.nc'
+  cf_out3=TRIM(cf_root)//'3.nc'
+  cf_out4=TRIM(cf_root)//'_minmax.nc'
 
   IF ( lzermean ) THEN
     lchk = lchk .OR. chkfile ( cn_fhgr )
@@ -170,33 +213,30 @@ PROGRAM cdfmoy
 
   cf_in = cf_list(1)
   IF ( chkfile (cf_in) ) STOP ! missing file
-
+!
   npiglo = getdim (cf_in, cn_x)
   npjglo = getdim (cf_in, cn_y)
-  npk    = getdim (cf_in, cn_z, cdtrue=cv_dep, kstatus=ierr)
-
-  IF (ierr /= 0 ) THEN
-     npk   = getdim (cf_in, 'z',cdtrue=cv_dep,kstatus=ierr)
-     IF (ierr /= 0 ) THEN
-       npk   = getdim (cf_in,'sigma',cdtrue=cv_dep,kstatus=ierr)
-        IF ( ierr /= 0 ) THEN 
-          npk = getdim (cf_in,'nav_lev',cdtrue=cv_dep,kstatus=ierr)
-            IF ( ierr /= 0 ) THEN 
-              npk = getdim (cf_in,'levels',cdtrue=cv_dep,kstatus=ierr)
-              IF ( ierr /= 0 ) THEN 
-                PRINT *,' assume file with no depth'
-                npk=0
-              ENDIF
-            ENDIF
-        ENDIF
-     ENDIF
+  
+  ! looking for npk among various possible name
+  idep_max=8
+  ALLOCATE ( clv_dep(idep_max) )
+  clv_dep(:) = (/cn_z,'z','sigma','nav_lev','levels','ncatice','icbcla','icbsect'/)
+  idep=1  ; ierr=1000
+  DO WHILE ( ierr /= 0 .AND. idep <= idep_max )
+     npk  = getdim (cf_in, clv_dep(idep), cdtrue=cv_dep, kstatus=ierr)
+     idep = idep + 1
+  ENDDO
+
+  IF ( ierr /= 0 ) THEN  ! none of the dim name was found
+      PRINT *,' assume file with no depth'
+      npk=0
   ENDIF
 
   PRINT *, 'npiglo = ', npiglo
   PRINT *, 'npjglo = ', npjglo
-  PRINT *, 'npk    = ', npk
+  PRINT *, 'npk    = ', npk , 'Dep name :' , TRIM(cv_dep)
 
-  ALLOCATE( dtab(npiglo,npjglo), dtab2(npiglo,npjglo), v2d(npiglo,npjglo) )
+  ALLOCATE( dtab(npiglo,npjglo), dtab2(npiglo,npjglo), v2d(npiglo,npjglo),rmask2d(npiglo,npjglo)) ! [from SL]
   ALLOCATE( rmean(npiglo,npjglo), rmean2(npiglo,npjglo) )
   IF ( lcubic ) THEN
      ALLOCATE( dtab3(npiglo,npjglo), rmean3(npiglo,npjglo) )
@@ -211,15 +251,27 @@ PROGRAM cdfmoy
   IF ( lcubic ) THEN
      ALLOCATE (cv_nam3(nvars), stypvar3(nvars), id_varout3(nvars)  )
   ENDIF
+  IF ( lmax ) THEN
+     ALLOCATE ( ipk4(2*nvars) )
+     ALLOCATE ( cv_nam4(2*nvars), stypvar4(2*nvars), id_varout4(2*nvars)  )
+     ALLOCATE ( rmin(npiglo, npjglo), rmax(npiglo,npjglo) )
+  ENDIF
 
   ! get list of variable names and collect attributes in stypvar (optional)
   cv_nam(:) = getvarname(cf_in,nvars,stypvar)
 
+  ! choose chunk size for output ... not easy not used if lnc4=.false. but anyway ..
+  DO jv = 1, nvars
+     stypvar(jv)%ichunk=(/npiglo,MAX(1,npjglo/30),1,1 /)
+     stypvar2(jv)%ichunk=(/npiglo,MAX(1,npjglo/30),1,1 /)
+  ENDDO
+
   IF ( lspval0 ) THEN 
      ALLOCATE ( zspval_in(nvars) )
      zspval_in(:) = stypvar(:)%rmissing_value
      stypvar(:)%rmissing_value = 0.
   ENDIF
+
   IF ( lcubic) THEN
      ! force votemper to be squared saved
      nn_sqdvar = nn_sqdvar + 1
@@ -238,13 +290,14 @@ PROGRAM cdfmoy
         stypvar2(jvar)%scale_factor      = 1.
         stypvar2(jvar)%add_offset        = 0.
         stypvar2(jvar)%savelog10         = 0.
-        stypvar2(jvar)%clong_name        = TRIM(stypvar(jvar)%clong_name)//'_Squared'   ! 
+        stypvar2(jvar)%clong_name        = TRIM(stypvar(jvar)%clong_name)//'_Squared'  ! 
         stypvar2(jvar)%cshort_name       = TRIM(stypvar(jvar)%cshort_name)//'_sqd'     !
         stypvar2(jvar)%conline_operation = TRIM(stypvar(jvar)%conline_operation) 
         stypvar2(jvar)%caxis             = TRIM(stypvar(jvar)%caxis) 
      ELSE
          cv_nam2(jvar) = 'none'
      END IF
+
      ! check for cubic average
      IF ( lcubic ) THEN
        IF ( varchk3 ( cv_nam(jvar) ) ) THEN 
@@ -258,12 +311,48 @@ PROGRAM cdfmoy
           stypvar3(jvar)%add_offset        = 0.
           stypvar3(jvar)%savelog10         = 0.
           stypvar3(jvar)%clong_name        = TRIM(stypvar(jvar)%clong_name)//'_Cubed'   ! 
-          stypvar3(jvar)%cshort_name       = TRIM(stypvar(jvar)%cshort_name)//'_cub'     !
+          stypvar3(jvar)%cshort_name       = TRIM(stypvar(jvar)%cshort_name)//'_cub'    !
           stypvar3(jvar)%conline_operation = TRIM(stypvar(jvar)%conline_operation) 
           stypvar3(jvar)%caxis             = TRIM(stypvar(jvar)%caxis) 
+
+          stypvar3(jvar)%ichunk=(/npiglo,MAX(1,npjglo/30),1,1 /)
        ELSE
           cv_nam3(jvar) = 'none'
        END IF
+     ENDIF  
+
+     IF ( lmax ) THEN
+          cv_nam4(jvar)                    = TRIM(cv_nam(jvar))//'_max'
+          stypvar4(jvar)%cname             = TRIM(stypvar(jvar)%cname)//'_max'         ! name
+          stypvar4(jvar)%cunits            = '('//TRIM(stypvar(jvar)%cunits)//')'      ! unit
+          stypvar4(jvar)%rmissing_value    = stypvar(jvar)%rmissing_value              ! missing_value
+          stypvar4(jvar)%valid_min         = 0.                                        ! valid_min = zero
+          stypvar4(jvar)%valid_max         = stypvar(jvar)%valid_max                   ! valid_max *valid_max
+          stypvar4(jvar)%scale_factor      = 1.
+          stypvar4(jvar)%add_offset        = 0.
+          stypvar4(jvar)%savelog10         = 0.
+          stypvar4(jvar)%clong_name        = TRIM(stypvar(jvar)%clong_name)//'_max'   ! 
+          stypvar4(jvar)%cshort_name       = TRIM(stypvar(jvar)%cshort_name)//'_max'  !
+          stypvar4(jvar)%conline_operation = TRIM(stypvar(jvar)%conline_operation)
+          stypvar4(jvar)%caxis             = TRIM(stypvar(jvar)%caxis)
+
+          stypvar4(jvar)%ichunk=(/npiglo,MAX(1,npjglo/30),1,1 /)
+      
+          cv_nam4(nvars+jvar)                    = TRIM(cv_nam(jvar))//'_min'
+          stypvar4(nvars+jvar)%cname             = TRIM(stypvar(jvar)%cname)//'_min'         ! name
+          stypvar4(nvars+jvar)%cunits            = '('//TRIM(stypvar(jvar)%cunits)//')'      ! unit
+          stypvar4(nvars+jvar)%rmissing_value    = stypvar(jvar)%rmissing_value              ! missing_value
+          stypvar4(nvars+jvar)%valid_min         = 0.                                        ! valid_min = zero
+          stypvar4(nvars+jvar)%valid_max         = stypvar(jvar)%valid_max                   ! valid_max *valid_max
+          stypvar4(nvars+jvar)%scale_factor      = 1.
+          stypvar4(nvars+jvar)%add_offset        = 0.
+          stypvar4(nvars+jvar)%savelog10         = 0.
+          stypvar4(nvars+jvar)%clong_name        = TRIM(stypvar(jvar)%clong_name)//'_min'   ! 
+          stypvar4(nvars+jvar)%cshort_name       = TRIM(stypvar(jvar)%cshort_name)//'_min'  !
+          stypvar4(nvars+jvar)%conline_operation = TRIM(stypvar(jvar)%conline_operation)
+          stypvar4(nvars+jvar)%caxis             = TRIM(stypvar(jvar)%caxis)
+
+          stypvar4(nvars+jvar)%ichunk=(/npiglo,MAX(1,npjglo/30),1,1 /)
      ENDIF
 
 
@@ -273,27 +362,40 @@ PROGRAM cdfmoy
   ! ipk gives the number of level or 0 if not a T[Z]YX  variable
   ipk(:)     = getipk (cf_in,nvars,cdep=cv_dep)
   WHERE( ipk == 0 ) cv_nam='none'
+  IF ( lmax ) THEN 
+      ipk4(1      :nvars  ) = ipk(1:nvars)
+      ipk4(nvars+1:2*nvars) = ipk(1:nvars)
+      WHERE( ipk4 == 0 ) cv_nam4='none'
+  ENDIF
                 stypvar (:)%cname = cv_nam
                 stypvar2(:)%cname = cv_nam2
   IF ( lcubic ) stypvar3(:)%cname = cv_nam3
+  IF ( lmax   ) stypvar4(:)%cname = cv_nam4
 
   ! create output file taking the sizes in cf_in
-  ncout  = create      (cf_out,  cf_in,    npiglo, npjglo, npk, cdep=cv_dep)
-  ierr   = createvar   (ncout ,  stypvar,  nvars,  ipk,    id_varout       )
-  ierr   = putheadervar(ncout,   cf_in,    npiglo, npjglo, npk, cdep=cv_dep)
+  ncout  = create      (cf_out,  cf_in,    npiglo, npjglo, npk, cdep=cv_dep, ld_nc4=lnc4)
+  ierr   = createvar   (ncout ,  stypvar,  nvars,  ipk,    id_varout       , ld_nc4=lnc4)
+  ierr   = putheadervar(ncout,   cf_in,    npiglo, npjglo, npk, cdep=cv_dep      )
 
-  ncout2 = create      (cf_out2, cf_in,    npiglo, npjglo, npk, cdep=cv_dep)
-  ierr   = createvar   (ncout2,  stypvar2, nvars,  ipk,    id_varout2      )
-  ierr   = putheadervar(ncout2,  cf_in,    npiglo, npjglo, npk, cdep=cv_dep)
+  ncout2 = create      (cf_out2, cf_in,    npiglo, npjglo, npk, cdep=cv_dep, ld_nc4=lnc4)
+  ierr   = createvar   (ncout2,  stypvar2, nvars,  ipk,    id_varout2      , ld_nc4=lnc4)
+  ierr   = putheadervar(ncout2,  cf_in,    npiglo, npjglo, npk, cdep=cv_dep      )
 
   IF ( lcubic) THEN
-     ncout3 = create      (cf_out3, cf_in,    npiglo, npjglo, npk, cdep=cv_dep)
-     ierr   = createvar   (ncout3,  stypvar3, nvars,  ipk,    id_varout3      )
-     ierr   = putheadervar(ncout3,  cf_in,    npiglo, npjglo, npk, cdep=cv_dep)
+     ncout3 = create      (cf_out3, cf_in,    npiglo, npjglo, npk, cdep=cv_dep, ld_nc4=lnc4)
+     ierr   = createvar   (ncout3,  stypvar3, nvars,  ipk,    id_varout3      , ld_nc4=lnc4)
+     ierr   = putheadervar(ncout3,  cf_in,    npiglo, npjglo, npk, cdep=cv_dep      )
+  ENDIF
+
+  IF ( lmax ) THEN
+     ncout4 = create      (cf_out4, cf_in,    npiglo, npjglo, npk, cdep=cv_dep, ld_nc4=lnc4)
+     ierr   = createvar   (ncout4,  stypvar4, 2*nvars,  ipk4,    id_varout4   , ld_nc4=lnc4)
+     ierr   = putheadervar(ncout4,  cf_in,    npiglo, npjglo, npk, cdep=cv_dep      )
   ENDIF
 
   lcaltmean=.TRUE.
   DO jvar = 1,nvars
+     iwght=0
      IF ( cv_nam(jvar) == cn_vlon2d .OR. &     ! nav_lon
           cv_nam(jvar) == cn_vlat2d ) THEN     ! nav_lat
         ! skip these variable
@@ -302,12 +404,15 @@ PROGRAM cdfmoy
         DO jk = 1, ipk(jvar)
            PRINT *,'level ',jk
            dtab(:,:) = 0.d0 ; dtab2(:,:) = 0.d0 ; dtotal_time = 0.
-           IF ( lcubic ) THEN  ; dtab3(:,:) = 0.d0 ; ENDIF
+           rmask2d(:,:) = 1.
+           IF ( lcubic ) THEN  ; dtab3(:,:) = 0.d0                       ; ENDIF
+           IF ( lmax   ) THEN  ; rmin (:,:) = 1.e20 ; rmax(:,:) = -1.e20 ; ENDIF
            ntframe = 0
            DO jfil = 1, nfil
               cf_in = cf_list(jfil)
               IF ( jk == 1 ) THEN
                   IF ( chkfile (cf_in) ) STOP ! missing file
+                  iwght=iwght+MAX(1,INT(getatt( cf_in, cv_nam(jvar), 'iweight')))
               ENDIF
 
               npt = getdim (cf_in, cn_t)
@@ -321,38 +426,55 @@ PROGRAM cdfmoy
                 ntframe = ntframe + 1
                 v2d(:,:)  = getvar(cf_in, cv_nam(jvar), jk ,npiglo, npjglo,ktime=jt )
                 IF ( lspval0  )  WHERE (v2d == zspval_in(jvar))  v2d = 0.  ! change missing values to 0
+                WHERE (v2d == 0.) rmask2d = 0.                              ! [from SL]
                 IF ( lzermean ) CALL zeromean (jk, v2d )
                 dtab(:,:) = dtab(:,:) + v2d(:,:)*1.d0
                 IF (cv_nam2(jvar) /= 'none' ) dtab2(:,:) = dtab2(:,:) + v2d(:,:)*v2d(:,:)*1.d0
                 IF ( lcubic ) THEN
                    IF (cv_nam3(jvar) /= 'none' ) dtab3(:,:) = dtab3(:,:) + v2d(:,:)*v2d(:,:)*v2d(:,:) *1.d0
                 ENDIF
+                IF ( lmax ) THEN
+                  rmax(:,:) = MAX(v2d(:,:),rmax(:,:))
+                  rmin(:,:) = MIN(v2d(:,:),rmin(:,:))
+                ENDIF
               ENDDO
            END DO
            ! finish with level jk ; compute mean (assume spval is 0 )
            rmean(:,:) = dtab(:,:)/ntframe
-           IF (cv_nam2(jvar) /= 'none' ) rmean2(:,:) = dtab2(:,:)/ntframe
+           IF ( lnomissincl ) rmean(:,:) = rmean(:,:)*(rmask2d(:,:)*1.d0)    ! [from SL]
+           IF (cv_nam2(jvar) /= 'none' ) THEN
+                rmean2(:,:) = dtab2(:,:)/ntframe
+                IF ( lnomissincl ) rmean2(:,:) = rmean2(:,:)*(rmask2d(:,:)*1.d0)    ! [from SL]
+           ENDIF
            IF ( lcubic ) THEN
-              IF (cv_nam3(jvar) /= 'none' ) rmean3(:,:) = dtab3(:,:)/ntframe
+              IF (cv_nam3(jvar) /= 'none' ) THEN 
+                  rmean3(:,:) = dtab3(:,:)/ntframe
+                  IF ( lnomissincl ) rmean3(:,:) = rmean3(:,:)*(rmask2d(:,:)*1.d0)    ! [from SL]
+              ENDIF
            ENDIF
 
            ! store variable on outputfile
-           ierr = putvar(ncout, id_varout(jvar), rmean, jk, npiglo, npjglo, kwght=ntframe)
+           ierr = putvar(ncout, id_varout(jvar), rmean, jk, npiglo, npjglo, kwght=iwght)
            IF (cv_nam2(jvar) /= 'none' ) THEN 
-               ierr = putvar(ncout2, id_varout2(jvar), rmean2, jk, npiglo, npjglo, kwght=ntframe)
+               ierr = putvar(ncout2, id_varout2(jvar), rmean2, jk, npiglo, npjglo, kwght=iwght)
            ENDIF
 
            IF ( lcubic) THEN
               IF (cv_nam3(jvar) /= 'none' ) THEN 
-                 ierr = putvar(ncout3, id_varout3(jvar), rmean3, jk, npiglo, npjglo, kwght=ntframe)
+                 ierr = putvar(ncout3, id_varout3(jvar), rmean3, jk, npiglo, npjglo, kwght=iwght)
               ENDIF
            ENDIF
+           IF ( lmax  ) THEN
+                 ierr = putvar(ncout4, id_varout4(      jvar), rmax, jk, npiglo, npjglo, kwght=iwght)
+                 ierr = putvar(ncout4, id_varout4(nvars+jvar), rmin, jk, npiglo, npjglo, kwght=iwght)
+           ENDIF
 
            IF (lcaltmean )  THEN
               timean(1) = dtotal_time/ntframe
                           ierr = putvar1d(ncout,  timean, 1, 'T')
                           ierr = putvar1d(ncout2, timean, 1, 'T')
               IF (lcubic) ierr = putvar1d(ncout3, timean, 1, 'T')
+              IF (lmax  ) ierr = putvar1d(ncout4, timean, 1, 'T')
            END IF
 
            lcaltmean=.FALSE. ! tmean already computed
@@ -363,6 +485,7 @@ PROGRAM cdfmoy
                 ierr = closeout(ncout)
                 ierr = closeout(ncout2)
   IF ( lcubic ) ierr = closeout(ncout3 ) 
+  IF ( lmax   ) ierr = closeout(ncout4 ) 
 
 CONTAINS 
 
diff --git a/src/cdfmoy_freq.f90 b/src/cdfmoy_freq.f90
new file mode 100644
index 0000000..1745aef
--- /dev/null
+++ b/src/cdfmoy_freq.f90
@@ -0,0 +1,367 @@
+PROGRAM cdfmoy_freq
+  !!======================================================================
+  !!                     ***  PROGRAM  cdfmoy_freq  ***
+  !!=====================================================================
+  !!  ** Purpose : Mainly in case of forcing file (gathered as yearly file)
+  !!               compute annual mean, monthl mean or diurnal means.
+  !!
+  !!  ** Method  : Detect the frequency of the input file according to the
+  !!               number of fields in the file.
+  !!
+  !! History : 2.1  : 06/2007  : P. Mathiot   : Original code from cdfmoy
+  !!           3.0  : 06/2011  : J.M. Molines : Doctor norm + Lic.
+  !!           3.0  : 10/2011  : P. Mathiot   : Add seasonal option and 
+  !!                                            allow file with 73 time steps
+  !!                : 05/2015  : J.M. Molines : Rewrite to be compliant with XIOS
+  !!----------------------------------------------------------------------
+  USE cdfio 
+  USE modcdfnames
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id$
+  !! Copyright (c) 2011, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)                               :: jk, jvar    ! dummy loop index
+  INTEGER(KIND=4)                               :: jv, jtt     ! dummy loop index
+  INTEGER(KIND=4)                               :: jframe      ! dummy loop index
+  INTEGER(KIND=4)                               :: it1, it2    ! box limits
+  INTEGER(KIND=4)                               :: ierr        ! working integer
+  INTEGER(KIND=4)                               :: narg, iargc     ! 
+  INTEGER(KIND=4)                               :: ijarg, ijm
+  INTEGER(KIND=4)                               :: npiglo, npjglo  ! size of the domain
+  INTEGER(KIND=4)                               :: npk ,npt        ! size of the domain
+  INTEGER(KIND=4)                               :: ip, nf          ! working integer
+  INTEGER(KIND=4)                               :: nvars           ! Number of variables in a file
+  INTEGER(KIND=4)                               :: nframes         ! Number of frames in the output file
+  INTEGER(KIND=4)                               :: ndyr, nhyr      ! Days and hours per year
+  INTEGER(KIND=4)                               :: nhfri           ! input freq in hours
+  INTEGER(KIND=4)                               :: ncout, ncout2
+  INTEGER(KIND=4), DIMENSION( 12)               :: njm             ! month vector
+  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_var, ipk, id_varout, ibox
+
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: v2d, rmean
+  REAL(KIND=4), DIMENSION(:,:,:),   ALLOCATABLE :: v3d
+  REAL(KIND=4), DIMENSION(:,:,:,:), ALLOCATABLE :: v4d
+  REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: time, time_mean
+
+  REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: dtab         ! Arrays for cumulated values
+  REAL(KIND=8)                                  :: dtotal_time
+
+  CHARACTER(LEN=256)                            :: cf_in               !
+  CHARACTER(LEN=256)                            :: cf_out='cdfmoy_'    ! file name
+  CHARACTER(LEN=256)                            :: cv_dep
+  CHARACTER(LEN=256)                            :: cfreq_o             ! output frequency
+  CHARACTER(LEN=256)                            :: cldum               ! dummy character arguments
+  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_names            ! array of var nam
+  CHARACTER(LEN=2  ), DIMENSION(4)              :: cfreq_a=(/'h ','d ','mo','y '/) ! authorized keys for frequency specif
+  CHARACTER(LEN=2  )                            :: cfr_id              ! current output freq id
+
+  TYPE (variable), DIMENSION(:),    ALLOCATABLE :: stypvar
+
+  LOGICAL                                       :: lcaltmean=.TRUE.
+  LOGICAL                                       :: lleap
+  LOGICAL                                       :: lerr
+  LOGICAL                                       :: lnc4 = .FALSE.
+  LOGICAL                                       :: lv3d = .FALSE.
+  LOGICAL                                       :: lv4d = .FALSE.
+  !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  narg= iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage : cdfmoy_freq -i IN-file -f averaging-length [ -v3d] [-v4d] '
+     PRINT *,'              [-nc4] [-o output root] '
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'       This program takes a file covering 1 year of data (evenly spaced)'
+     PRINT *,'       and sub-samples the data by performing box averages, which span is given'
+     PRINT *,'       as argument.  The original data sampling can be hours, days or monthes '
+     PRINT *,'       or even seasons.'
+     PRINT *,'       The program recognizes leap years, and when feb. 29 is found, it is '
+     PRINT *,'       included in the current ''box'' (averaging length is thus increased'
+     PRINT *,'       by 1 day.'
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       -i IN-file : gives the name of the yearly file containing either 365 '
+     PRINT *,'                  or 366 days'
+     PRINT *,'       -f averaging-length : Set the time size of the averaging box. '
+     PRINT *,'                 Averaging length is specified using XIOS convention (e.g. 1d,'
+     PRINT *,'                 5d, 1mo, 1y ; 4mo stands for seasonal means )'
+     PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'       [-v3d] : use 3d variable (x,y,t) : save execution time, increase memory'
+     PRINT *,'       [-v4d] : use 4d variable (x,y,z,t): save execution time, increase memory'
+     PRINT *,'       [-nc4] : use netcdf4 with chunking and deflation for the output file'
+     PRINT *,'       [-o output_root] : specify the root of the output file name instead '
+     PRINT *,'                   of ',TRIM(cf_out),'. Final name will have <freq> appened'
+     PRINT *,'                   to the root.'
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'        none.'
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file :  cdfmoy_output<freq>.nc'
+     PRINT *,'         variables :  same as variables in input file.'
+     PRINT *,'      '
+     PRINT *,'     SEE ALSO :'
+     PRINT *,'      cdfmoy, cdfmoy_weighted'
+     PRINT *,'      '
+     STOP
+  ENDIF
+
+  ! parse command line
+  ijarg = 1
+  DO WHILE ( ijarg <= narg )
+     CALL getarg(ijarg, cldum) ; ijarg = ijarg +1
+     SELECT CASE ( cldum ) 
+     CASE ( '-i'   ) ; CALL getarg(ijarg, cf_in   ) ; ijarg = ijarg + 1
+     CASE ( '-f'   ) ; CALL getarg(ijarg, cfreq_o ) ; ijarg = ijarg + 1
+     CASE ( '-o'   ) ; CALL getarg(ijarg, cf_out  ) ; ijarg = ijarg + 1
+     CASE ( '-nc4' ) ; lnc4=.TRUE.
+     CASE ( '-v3d' ) ; lv3d=.TRUE.
+     CASE ( '-v4d' ) ; lv4d=.TRUE.
+     CASE DEFAULT 
+        PRINT *,' +++ ERROR : Option ', TRIM(cldum) ,' not understood !'
+        STOP 1
+     END SELECT
+  END DO
+
+  IF ( chkfile ( cf_in ) ) STOP ! missing file
+
+  ! parse the cfreqo to determine the output frequency. 
+  ! Allowed syntax is nf<cfr_id> where nf is an integer >0, <cfr_id> is h, d, mo or y
+  cfr_id='--'
+  DO jk =1, 4
+     ip=INDEX(cfreq_o, cfreq_a(jk) )
+     IF ( ip /= 0 ) THEN
+        cfr_id=cfreq_o(ip:)
+        READ(cfreq_o(1:ip-1), *) nf
+        EXIT
+     ENDIF
+  ENDDO
+
+  SELECT CASE ( cfr_id )
+  CASE ( '--' ) 
+     PRINT *, ' +++ ERROR : Cannot determine the output frequency'
+     PRINT *, '            You should use a character string such as 6h, 5d, 1mo, 1y '
+  CASE ( 'd' ) 
+     IF ( nf /= 1 .AND. nf/=5 ) THEN
+        PRINT *, ' +++ ERROR : only 1d or 5d are acceptable !'
+        STOP
+     ENDIF
+  CASE ( 'y' )
+     IF ( nf > 1 ) THEN
+        PRINT *, ' +++ ERROR : Cannot have output freq > 1 y !'
+        STOP
+     ENDIF
+  END SELECT
+
+  ! get domain size from the input file
+  npiglo= getdim (cf_in, cn_x                             )
+  npjglo= getdim (cf_in, cn_y                             )
+  npk   = getdim (cf_in, cn_z, cdtrue=cv_dep, kstatus=ierr)
+
+  IF (ierr /= 0 ) THEN
+     npk   = getdim (cf_in,'z',cdtrue=cv_dep,kstatus=ierr)
+     IF (ierr /= 0 ) THEN
+        npk   = getdim (cf_in,'sigma',cdtrue=cv_dep,kstatus=ierr)
+        IF ( ierr /= 0 ) THEN 
+           PRINT *,' assume file with no depth'
+           npk=0
+        ENDIF
+     ENDIF
+  ENDIF
+
+  npt   = getdim (cf_in, cn_t)
+
+  ! Now look at input file and try to look for input frequency
+  ! Note that we know that the file contains either 365d or 366 days of data
+  ! We suppose that input file freq is a multiple of 1 hour.
+  lleap = .FALSE.
+  ndyr  = 365     ! number of days per year
+  nhyr  = ndyr*24 ! number of hours per year
+
+  IF ( MOD( nhyr, npt ) /= 0 ) THEN
+     ndyr = 366     ! try leap year
+     nhyr = ndyr*24 ! number of hours per leap year
+     IF ( MOD( nhyr, npt ) /= 0 ) THEN
+        PRINT *," +++ ERROR : npt do not fit in 365 nor 366 days "
+        STOP
+     ELSE
+        lleap=.TRUE.
+     ENDIF
+  ENDIF
+  nhfri = 24*ndyr/npt  ! input frequency in hours
+
+  PRINT *, 'INPUT FILE : ', TRIM(cf_in)
+  PRINT *, 'NPIGLO = ', npiglo
+  PRINT *, 'NPJGLO = ', npjglo
+  PRINT *, 'NPK    = ', npk
+  PRINT *, 'NPT    = ', npt
+  PRINT *, ' '
+  PRINT *, ' LEAP YEAR  : ', lleap
+  PRINT *, ' INPUT FREQ : ', nhfri,' hours '
+
+  ! Now determines the number of frames in the output file and detect impossible case
+  !  Also determines the number of input frames in boxes. (can be variable)
+  ! number of day by month
+  njm(:)= (/ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 /)
+
+  IF ( lleap ) THEN 
+     njm(:) = (/ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 /)
+  ENDIF
+
+  lerr = .TRUE.
+  SELECT CASE ( cfr_id )
+  CASE ( 'h' ) 
+     IF ( MOD( nf, nhfri ) == 0 ) THEN
+        nframes = ndyr*24/nf 
+        ALLOCATE (ibox( nframes) )
+        ibox(:)=nf/nhfri ; lerr=.FALSE.
+     ENDIF
+  CASE ( 'd' ) ! note : 365 = 73 *5  ( 366 = 73 *5 + 1 ) 
+     IF ( MOD ( nf*24, nhfri ) == 0 ) THEN
+        IF ( nf == 1 ) nframes = ndyr
+        IF ( nf == 5 ) nframes = 73  ! in case of leap year frame#12 will have 6day average
+        ALLOCATE (ibox( nframes) )
+        lerr=.FALSE.
+        ibox(:)=nf*24/nhfri 
+        IF ( lleap .AND. nf == 5 ) ibox(12)=6*24/nhfri
+     ENDIF
+  CASE ( 'mo' )
+     !##################################
+     !JM : do not work if nhfri > 24 !!! 
+     !##################################
+     IF ( MOD( 12, nf ) == 0 ) THEN
+        nframes=12/nf ; lerr=.FALSE.
+        ALLOCATE (ibox( nframes) )  ! 12 6 4 3 2 
+        SELECT CASE ( nframes )
+        CASE ( 12 )
+           ibox(:) = njm(:)*24/nhfri 
+        CASE ( 6 )
+           DO jframe= 1, nframes
+              ijm=jframe*2-1
+              ibox(jframe) = (njm(ijm)+njm(ijm+1)) *24/nhfri 
+           ENDDO
+        CASE ( 4 )
+           DO jframe= 1, nframes
+              ijm=jframe*3-2
+              ibox(jframe) = (njm(ijm)+njm(ijm+1)+njm(ijm+2)) *24/nhfri 
+           ENDDO
+        CASE ( 3 )
+           DO jframe= 1, nframes
+              ijm=jframe*4-3
+              ibox(jframe) = (njm(ijm)+njm(ijm+1)+njm(ijm+2)+njm(ijm+3)) *24/nhfri 
+           ENDDO
+        CASE ( 2 )
+           DO jframe= 1, nframes
+              ijm=jframe*6-5
+              ibox(jframe) = (njm(ijm)+njm(ijm+1)+njm(ijm+2)+njm(ijm+3)+njm(ijm+4)+njm(ijm+5)) *24/nhfri 
+           ENDDO
+        END SELECT
+     ENDIF
+  CASE ( 'y' )  ! 1y average  all is to be taken !
+     nframes = 1
+     ALLOCATE (ibox( nframes) )
+     ibox(:) = npt
+     lerr = .FALSE.
+  END SELECT
+
+  IF ( lerr ) THEN
+     PRINT *, ' +++ ERROR : Input and output frequency incompatible.'
+     PRINT *, '         Input  : ',  nhfri,' hours '
+     PRINT *, '         Output : ',  nf,' hours '
+     STOP
+  ENDIF
+
+  ALLOCATE( dtab(npiglo,npjglo), v2d(npiglo,npjglo) )
+  ALLOCATE( rmean(npiglo,npjglo)                    )
+  IF (lv3d)   ALLOCATE( v3d(npiglo,npjglo,npt)      )
+
+  nvars = getnvar(cf_in)
+  PRINT *,' nvars =', nvars
+
+  ALLOCATE (cv_names(nvars)                            )
+  ALLOCATE (stypvar(nvars)                             )
+  ALLOCATE (id_var(nvars), ipk(nvars), id_varout(nvars))
+  ALLOCATE( time( npt), time_mean(nframes)             )
+
+  ! get list of variable names and collect attributes in stypvar (optional)
+  cv_names(:)=getvarname(cf_in, nvars, stypvar)
+
+  id_var(:)  = (/(jv, jv=1,nvars)/)
+  ! ipk gives the number of level or 0 if not a T[Z]YX  variable
+  ipk(:)     = getipk (cf_in, nvars, cdep=cv_dep)
+  !
+  WHERE( ipk == 0 ) cv_names='none'
+  stypvar(:)%cname = cv_names
+  DO jv=1, nvars
+    stypvar(jv)%ichunk=(/npiglo,MAX(1,npjglo/30), 1, 1 /)
+  ENDDO
+
+  ! create output file taking the sizes in cf_in
+  cf_out = TRIM(cf_out)//'_'//TRIM(cfreq_o)//'.nc'
+  ncout = create      (cf_out, cf_in,   npiglo, npjglo, npk, cdep=cv_dep , ld_nc4=lnc4 )
+  ierr  = createvar   (ncout,  stypvar, nvars,  ipk,    id_varout        , ld_nc4=lnc4 )
+  ierr  = putheadervar(ncout,  cf_in,   npiglo, npjglo, npk, cdep=cv_dep               )
+
+  time(:)=getvar1d(cf_in, cn_vtimec, npt)
+  DO jvar = 1,nvars
+     IF ( cv_names(jvar) == cn_vlon2d .OR.                            &
+          cv_names(jvar) == cn_vlat2d .OR. cv_names(jvar) == 'none') THEN
+        ! skip these variable
+     ELSE
+        PRINT *,' Working with ', TRIM(cv_names(jvar))
+        IF (lv4d)   ALLOCATE( v4d(npiglo, npjglo,ipk(jvar),npt)  )
+
+        IF (lv4d)  v4d(:,:,:,:) = getvar4d(cf_in, cv_names(jvar),npiglo, npjglo,ipk(jvar),npt)
+        DO jk=1,ipk(jvar)
+
+           ! initialisation
+           dtab(:,:) = 0.d0 ; dtotal_time = 0.d0
+
+           ! time loop
+           it1=1
+           IF ( lv3d )  v3d(:,:,:)=getvar3dt(cf_in, cv_names(jvar),jk,npiglo, npjglo, npt)
+           DO jframe = 1, nframes
+              it2=it1+ibox(jframe)-1
+              DO jtt=it1, it2
+                 ! load data
+                  IF ( lv4d) THEN 
+                       v2d(:,:) = v4d(:,:,jk,jtt)
+                  ELSE
+                    IF ( lv3d ) THEN
+                       v2d(:,:)  = v3d(:,:,jtt)
+                    ELSE
+                       v2d(:,:)  = getvar(cf_in, cv_names(jvar), jk, npiglo, npjglo, ktime=jtt )
+                    ENDIF
+                  ENDIF
+                 dtab(:,:) = dtab(:,:) + v2d(:,:)*1.d0
+                 IF ( lcaltmean ) THEN
+                    dtotal_time = dtotal_time + time(jtt) 
+                 ENDIF
+              ENDDO
+              rmean(:,:) = dtab(:,:)/ibox(jframe)
+              ierr = putvar(ncout, id_varout(jvar) ,rmean, jk, npiglo, npjglo, ktime=jframe)
+              IF ( lcaltmean ) THEN
+                 time_mean(jframe) = dtotal_time/ibox(jframe)
+              ENDIF
+              dtab(:,:) = 0.d0 ; dtotal_time = 0.d0
+              it1 = it2 + 1
+              !
+           ENDDO ! loop to next time
+           lcaltmean=.FALSE.
+
+        ENDDO ! loop to next level
+        IF (lv4d)   DEALLOCATE( v4d )
+     END IF
+  END DO ! loop to next var in file
+
+  ierr = putvar1d(ncout,   time_mean,  nframes  , 'T')
+  ierr = closeout(ncout)
+
+
+END PROGRAM cdfmoy_freq
diff --git a/cdfmoy_weighted.f90 b/src/cdfmoy_weighted.f90
similarity index 65%
rename from cdfmoy_weighted.f90
rename to src/cdfmoy_weighted.f90
index 58398df..24db728 100644
--- a/cdfmoy_weighted.f90
+++ b/src/cdfmoy_weighted.f90
@@ -1,11 +1,10 @@
-PROGRAM cdfmoy_weighted
+ PROGRAM cdfmoy_weighted
   !!======================================================================
   !!                     ***  PROGRAM  cdfmoy_weighted  ***
   !!=====================================================================
   !!  ** Purpose : Compute weighted mean values from already processed
   !!               mean files (by cdfmoy)
   !!
-  !!  ** Method  : The weight of each file is the number of elements used
   !!               when computing the time average. 
   !!
   !! History : 2.1  : 11/2009  : J.M. Molines : Original code
@@ -29,7 +28,7 @@ PROGRAM cdfmoy_weighted
   INTEGER(KIND=4)                               :: narg, iargc, ijarg  ! command line
   INTEGER(KIND=4)                               :: npiglo, npjglo, npk ! size of the domain
   INTEGER(KIND=4)                               :: nvars               ! number of variables in a file
-  INTEGER(KIND=4)                               :: ntags               ! number of tags to process
+  INTEGER(KIND=4)                               :: ixtra               ! number of tags to process
   INTEGER(KIND=4)                               :: iweight             ! variable weight
   INTEGER(KIND=4)                               :: ncout               ! ncid of output file
   INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_var              ! array of input var id's
@@ -37,26 +36,33 @@ PROGRAM cdfmoy_weighted
   INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_varout           ! array of output var id's
 
   REAL(KIND=4), DIMENSION (:,:),    ALLOCATABLE :: v2d                 ! array to read a layer of data
+  REAL(KIND=4), DIMENSION (:)  ,    ALLOCATABLE :: v1d                 ! array to read column of data
   REAL(KIND=4), DIMENSION(1)                    :: timean, tim         ! time counter
 
   REAL(KIND=8), DIMENSION (:,:),    ALLOCATABLE :: dtab                ! array for cumulated values
+  REAL(KIND=8), DIMENSION (:)  ,    ALLOCATABLE :: dtab1d              ! array for cumulated values
   REAL(KIND=8)                                  :: dtotal_time, dsumw  ! cumulated times and weights
 
   CHARACTER(LEN=256)                            :: cf_in               ! current input file name
   CHARACTER(LEN=256)                            :: cf_out='cdfmoy_weighted.nc' ! output file name
   CHARACTER(LEN=256)                            :: cv_dep              ! name of depth variable
+  CHARACTER(LEN=256)                            :: cv_skip             ! name of  variable to skip
   CHARACTER(LEN=256)                            :: cldum               ! dummy character variable
   CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_names            ! array of var name
-  
+
   TYPE (variable), DIMENSION(:),    ALLOCATABLE :: stypvar             ! structure for output var attributes
 
-  LOGICAL                                       :: lold5d              ! flag for old5d output
+  LOGICAL                                       :: lold5d=.FALSE.      ! flag for old5d output
+  LOGICAL                                       :: lmonth=.FALSE.      ! flag for true month output
+  LOGICAL                                       :: lleap=.FALSE.       ! flag for leap years
+  LOGICAL                                       :: lnc4=.FALSE.        ! flag for netcdf4 output with chunking and deflation
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
   narg= iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfmoy_weighted list of files [-old5d ]'
+     PRINT *,' usage : cdfmoy_weighted list of files [-old5d ] [-month] [-leap] ...'
+     PRINT *,'      [-skip variable] [-nc4] [-o output file]'
      PRINT *,'     PURPOSE :'
      PRINT *,'       Compute weight average of files. The weight for each file is'
      PRINT *,'       read from the iweight attribute. In particular, this attribute'
@@ -75,6 +81,14 @@ PROGRAM cdfmoy_weighted
      PRINT *,'                   files must be given, and it is assumed that the monthly'
      PRINT *,'                   means were computed from 5d output of a simulation using'
      PRINT *,'                   a noleap calendar ( weights are fixed, predetermined)'
+     PRINT *,'       [-month ] : This option is used to build annual mean from true month'
+     PRINT *,'                   output (1mo) in XIOS output for instance.'
+     PRINT *,'       [-leap ] : This option has only effect together with the -month option.'
+     PRINT *,'                  When used set 29 days in february'
+     PRINT *,'       [-skip variable ] : name of variable to skip '
+     PRINT *,'       [ -nc4 ] : Use netcdf4 chunking and deflation in output file.'
+     PRINT *,'       [-o output file ] : Specify the name for output file instead of the'
+     PRINT *,'                 default name ', TRIM(cf_out)
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'       none'
@@ -85,29 +99,30 @@ PROGRAM cdfmoy_weighted
      STOP
   ENDIF
 
-  ! default values
-  lold5d = .FALSE.
   ! scan command line and check if files exist
-  ijarg = 1
-  ntags = narg
+  ijarg = 1 ; ixtra=0
   DO WHILE ( ijarg <= narg ) 
-    CALL getarg ( ijarg, cldum ) ; ijarg = ijarg +1
-    SELECT CASE ( cldum )
-    CASE ( '-old5d' )
-        lold5d = .TRUE.
-        ntags = ntags - 1
-    CASE DEFAULT
+     CALL getarg ( ijarg, cldum ) ; ijarg = ijarg +1
+     SELECT CASE ( cldum )
+     CASE ( '-old5d' )  ; lold5d = .TRUE.
+     CASE ( '-month' )  ; lmonth = .TRUE.
+     CASE ( '-leap'  )  ; lleap  = .TRUE.
+     CASE ( '-nc4'   )  ; lnc4   = .TRUE.
+     CASE ( '-o'     )  ; CALL getarg ( ijarg, cf_out ) ; ijarg = ijarg +1
+     CASE ( '-skip'  )  ; CALL getarg ( ijarg, cv_skip) ; ijarg = ijarg +1
+     CASE DEFAULT
+        ixtra = ixtra + 1
         cf_in = cldum
         IF ( chkfile (cldum ) ) STOP ! missing file
-    END SELECT
+     END SELECT
   ENDDO
 
   ! additional check in case of old_5d averaged files
-  IF ( lold5d ) THEN
-    IF ( ntags /= 12 ) THEN 
-       PRINT *,' ERROR : exactly 12 monthly files are required for -old5d option'
-       STOP
-    ENDIF
+  IF ( lold5d .OR. lmonth ) THEN
+     IF ( ixtra /= 12 ) THEN 
+        PRINT *,' +++ ERROR : exactly 12 monthly files are required for -old5d/-month options.'
+        STOP
+     ENDIF
   ENDIF
 
   npiglo = getdim (cf_in, cn_x                              )
@@ -117,16 +132,16 @@ PROGRAM cdfmoy_weighted
   IF (ierr /= 0 ) THEN
      npk   = getdim (cf_in,'z',cdtrue=cv_dep, kstatus=ierr   )
      IF (ierr /= 0 ) THEN
-       npk   = getdim (cf_in,'sigma',cdtrue=cv_dep,kstatus=ierr)
+        npk   = getdim (cf_in,'sigma',cdtrue=cv_dep,kstatus=ierr)
         IF ( ierr /= 0 ) THEN
-          npk = getdim (cf_in,'nav_lev',cdtrue=cv_dep,kstatus=ierr)
-            IF ( ierr /= 0 ) THEN
+           npk = getdim (cf_in,'nav_lev',cdtrue=cv_dep,kstatus=ierr)
+           IF ( ierr /= 0 ) THEN
               npk = getdim (cf_in,'levels',cdtrue=cv_dep,kstatus=ierr)
               IF ( ierr /= 0 ) THEN
-                PRINT *,' assume file with no depth'
-                npk=0
+                 PRINT *,' assume file with no depth'
+                 npk=0
               ENDIF
-            ENDIF
+           ENDIF
         ENDIF
      ENDIF
   ENDIF
@@ -154,22 +169,46 @@ PROGRAM cdfmoy_weighted
   WHERE( ipk == 0 ) cv_names='none'
   stypvar(:)%cname = cv_names
 
+  DO jk = 1, nvars
+     stypvar(jk)%ichunk  = (/ npiglo, MAX(1,npjglo/30), 1, 1 /)
+  ENDDO
+
   ! create output file taking the sizes in cf_in
-  ncout = create      (cf_out, cf_in,   npiglo, npjglo, npk,      cdep=cv_dep )
-  ierr  = createvar   (ncout , stypvar, nvars,  ipk,    id_varout             )
-  ierr  = putheadervar(ncout , cf_in,   npiglo, npjglo, npk,      cdep=cv_dep )
+  ncout = create      (cf_out, cf_in,   npiglo, npjglo, npk,      cdep=cv_dep , ld_nc4=lnc4 )
+  ierr  = createvar   (ncout , stypvar, nvars,  ipk,    id_varout             , ld_nc4=lnc4 )
+  ierr  = putheadervar(ncout , cf_in,   npiglo, npjglo, npk,      cdep=cv_dep               )
 
   DO jvar = 1,nvars
      IF ( cv_names(jvar) == cn_vlon2d .OR. &
-          cv_names(jvar) == cn_vlat2d        ) THEN
+          cv_names(jvar) == cn_vlat2d .OR. &
+          cv_names(jvar) == 'none'    .OR. &
+          cv_names(jvar) == cv_skip        ) THEN
         ! skip these variable
      ELSE
         PRINT *,' Working with ', TRIM(cv_names(jvar)), ipk(jvar)
+        IF ( npiglo == 1 .AND. npjglo == 1 ) THEN 
+         !
+           ALLOCATE (v1d( ipk(jvar)), dtab1d(ipk(jvar)) )
+           dtab1d(:) = 0.d0 ; dtotal_time=0.d0 ; dsumw=0.d0
+           DO jt=1, ixtra
+              CALL getarg   (jt, cf_in)
+              iweight   = setweight(cf_in, jt, cv_names(jvar)) 
+              dsumw     = dsumw + iweight
+              tim = getvar1d(cf_in, cn_vtimec, 1 )
+              dtotal_time = dtotal_time + iweight * tim(1)
+              v1d=getvare3(cf_in, cv_names(jvar), ipk(jvar) )
+              dtab1d(:)=dtab1d(:) + iweight * v1d(:)
+           ENDDO
+           timean(1) = dtotal_time/dsumw
+           ierr      = putvar1d(ncout, timean, 1, 'T')
+           ierr      = putvar(ncout, id_varout(jvar), SNGL(dtab1d(:)/dsumw), ipk(jvar), 'vert', ktime=1 , kwght=INT(dsumw) )  ! module interface to putvare3
+           DEALLOCATE (v1d, dtab1d)
+        ELSE
         DO jk = 1, ipk(jvar)
            PRINT *,'Level ',jk
            dtab(:,:) = 0.d0 ; dtotal_time = 0.d0 ; dsumw=0.d0
 
-           DO jt = 1, ntags
+           DO jt = 1, ixtra
               CALL getarg   (jt, cf_in)
 
               iweight   = setweight(cf_in, jt, cv_names(jvar)) 
@@ -179,7 +218,7 @@ PROGRAM cdfmoy_weighted
 
               IF (jk == 1 .AND. jvar == nvars )  THEN
                  tim         = getvar1d(cf_in, cn_vtimec, 1 )
-                 dtotal_time = dtotal_time + tim(1)
+                 dtotal_time = dtotal_time + iweight * tim(1)
               END IF
            END DO
 
@@ -187,16 +226,17 @@ PROGRAM cdfmoy_weighted
            ! store variable on outputfile
            ierr = putvar(ncout, id_varout(jvar), SNGL(dtab(:,:)/dsumw), jk, npiglo, npjglo, kwght=INT(dsumw) )
            IF (jk == 1 .AND. jvar == nvars )  THEN
-              timean(1) = dtotal_time/ntags
+              timean(1) = dtotal_time/dsumw
               ierr      = putvar1d(ncout, timean, 1, 'T')
            END IF
         END DO  ! loop to next level
+        END IF ! 1D variable
      END IF
   END DO ! loop to next var in file
 
   ierr = closeout(ncout)
 
-  CONTAINS
+CONTAINS
 
   INTEGER(KIND=4) FUNCTION setweight( cdfile, kt, cdvar )
     !!---------------------------------------------------------------------
@@ -213,14 +253,22 @@ PROGRAM cdfmoy_weighted
     CHARACTER(LEN=*),   INTENT(in) :: cdvar
 
     INTEGER(KIND=4), DIMENSION(12) :: iweight5d=(/6,5,7,6,6,6,6,6,6,6,6,7/)
+    INTEGER(KIND=4), DIMENSION(12) :: iweightmo=(/31,28,31,30,31,30,31,31,30,31,30,31/)
+    INTEGER(KIND=4), DIMENSION(12) :: iweightleap=(/31,29,31,30,31,30,31,31,30,31,30,31/)
     !!----------------------------------------------------------------------
     IF ( lold5d ) THEN 
-      setweight = iweight5d(kt)
+       setweight = iweight5d(kt)
+    ELSE IF ( lmonth ) THEN
+       IF ( lleap ) THEN
+          setweight = iweightleap(kt)
+       ELSE
+          setweight = iweightmo(kt)
+       ENDIF
     ELSE
-      setweight = getatt( cdfile, cdvar, 'iweight') 
-      IF ( setweight == 0 ) setweight = 1
+       setweight = getatt( cdfile, cdvar, 'iweight') 
+       IF ( setweight == 0 ) setweight = 1
     ENDIF
 
-    END FUNCTION setweight
+  END FUNCTION setweight
 
 END PROGRAM cdfmoy_weighted
diff --git a/cdfmoyt.f90 b/src/cdfmoyt.f90
similarity index 100%
rename from cdfmoyt.f90
rename to src/cdfmoyt.f90
diff --git a/cdfmoyuvwt.f90 b/src/cdfmoyuvwt.f90
similarity index 100%
rename from cdfmoyuvwt.f90
rename to src/cdfmoyuvwt.f90
diff --git a/cdfmppini.f90 b/src/cdfmppini.f90
similarity index 99%
rename from cdfmppini.f90
rename to src/cdfmppini.f90
index f419342..e026b63 100644
--- a/cdfmppini.f90
+++ b/src/cdfmppini.f90
@@ -466,7 +466,7 @@ CONTAINS
       IF (lwp) THEN
          OPEN (inum, FILE=cf_out, FORM='FORMATTED', RECL=255)
          WRITE(inum,'(6i8)') jpnij,jpi,jpj,jpiglo,jpjglo
-         WRITE(inum,'(a)') 'RANK   nlci nlcj nldi nldj nlei nlej nimpp njmpp nono noso nowe noea nbondi nbondj '
+         WRITE(inum,'(a)') 'NAREA   nlci nlcj nldi nldj nlei nlej nimpp njmpp nono noso nowe noea nbondi nbondj '
 
         DO  jproc = 1, jpnij
          ii = iin(jproc)
@@ -475,7 +475,7 @@ CONTAINS
          nbondj(jproc) = ibondj(ii,ij)
          
 
-         WRITE(inum,'(15i5)') jproc-1, nlcit(jproc), nlcjt(jproc), &
+         WRITE(inum,'(15i5)') jproc  , nlcit(jproc), nlcjt(jproc), &
                                        nldit(jproc), nldjt(jproc), &
                                        nleit(jproc), nlejt(jproc), &
                                        nimppt(jproc), njmppt(jproc),& 
diff --git a/cdfmsk.f90 b/src/cdfmsk.f90
similarity index 100%
rename from cdfmsk.f90
rename to src/cdfmsk.f90
diff --git a/cdfmxl.f90 b/src/cdfmxl.f90
similarity index 91%
rename from cdfmxl.f90
rename to src/cdfmxl.f90
index eae42e8..06d81df 100644
--- a/cdfmxl.f90
+++ b/src/cdfmxl.f90
@@ -26,11 +26,12 @@ PROGRAM cdfmxl
   !!----------------------------------------------------------------------
   IMPLICIT NONE
 
-  INTEGER(KIND=4),PARAMETER                    :: pnvarout = 7   ! number of output variables 
+  INTEGER(KIND=4), PARAMETER                   :: jp_varout = 7  ! number of output variables 
   INTEGER(KIND=4)                              :: ji, jj, jk, jt ! dummy loop index
   INTEGER(KIND=4)                              :: ik1, ik2, ikt  ! k vertical index of mixed layers 
   INTEGER(KIND=4), DIMENSION(1)                :: nkref10        ! vertical index for 10m depth T layer  
   INTEGER(KIND=4)                              :: narg, iargc    ! browse line
+  INTEGER(KIND=4)                              :: ijarg, ixtra   ! browse line
   INTEGER(KIND=4)                              :: npiglo, npjglo ! domain size
   INTEGER(KIND=4)                              :: npk, npt       ! domain size
   INTEGER(KIND=4)                              :: ncout, ierr    ! ncid of output file, error status
@@ -42,7 +43,7 @@ PROGRAM cdfmxl
   INTEGER(KIND=4), DIMENSION(:,:), ALLOCATABLE :: nmlnt          ! last level where T - SST > temp_c
   INTEGER(KIND=4), DIMENSION(:,:), ALLOCATABLE :: nmlnt2         ! last level where T-T10 > temp_c  
   INTEGER(KIND=4), DIMENSION(:,:), ALLOCATABLE :: nmlnt3         ! last level where T-T10 > temp_c2 
-  INTEGER(KIND=4), DIMENSION(pnvarout)         :: ipk, id_varout ! levels and varid's of output vars
+  INTEGER(KIND=4), DIMENSION(jp_varout)        :: ipk, id_varout ! levels and varid's of output vars
 
   REAL(KIND=4)                                 :: rmisval=32767. ! Missing value of Mercator fields 
   REAL(KIND=4)                                 :: rr1,rr2        ! Coef for T(z=10m) interp. 
@@ -77,16 +78,18 @@ PROGRAM cdfmxl
   CHARACTER(LEN=256)                           :: cf_tfil        ! input T file
   CHARACTER(LEN=256)                           :: cf_sfil        ! input S file (F.Hernandez)
   CHARACTER(LEN=256)                           :: cf_out='mxl.nc'! output file name
+  CHARACTER(LEN=256)                           :: cldum          ! dummy character variable
 
-  TYPE(variable), DIMENSION(pnvarout)          :: stypvar        ! structure for attributes 
+  TYPE(variable), DIMENSION(jp_varout)         :: stypvar        ! structure for attributes 
 
   LOGICAL                                      :: lexist         ! flag for existence of bathy_level file
+  LOGICAL                                      :: lnc4=.FALSE.   ! flag for netcdf4 output with chunking and deflation
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
   narg = iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfmxl T-file [S-file]'
+     PRINT *,' usage : cdfmxl T-file [S-file] [-nc4] [-o output file]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
      PRINT *,'       Compute 7 estimates of the mixed layer depth from temperature'
@@ -106,6 +109,11 @@ PROGRAM cdfmxl
      PRINT *,'       T-file   : input netcdf file (gridT)' 
      PRINT *,'       [S-file] : input netcdf file (gridS) Optional if vosaline not in T-file' 
      PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'       [-nc4] : use netcdf4 chunking and deflation on output '
+     PRINT *,'       [-o output file] : specify the name of output file instead of '
+     PRINT *,'                default name ',TRIM(cf_out)
+     PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'        ',TRIM(cn_fzgr)
      PRINT *,'         In case of FULL STEP configuration, ',TRIM(cn_fbathylev),' is also required.'
@@ -122,13 +130,23 @@ PROGRAM cdfmxl
      STOP
   ENDIF
 
-  CALL getarg (1, cf_tfil)
-  cf_sfil = cf_tfil  ! default case
-
-  ! If second argument file --> for salinity 
-  IF ( narg == 2 ) THEN
-     CALL getarg (2, cf_sfil)
-  ENDIF
+  ijarg = 1 ; ixtra = 0
+  DO WHILE ( ijarg <= narg )
+    CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1
+    SELECT CASE (cldum )
+    CASE ( '-nc4' ) ; lnc4 = .TRUE.
+    CASE ( '-o'   ) ; CALL getarg (ijarg,cf_out )   ; ijarg = ijarg + 1
+    CASE DEFAULT
+      ixtra = ixtra + 1
+      SELECT CASE (ixtra )
+      CASE ( 1 ) ; cf_tfil = cldum ; cf_sfil = cf_tfil  ! first free name is a gridT file name
+      CASE ( 2 ) ; cf_sfil = cldum                      ! second free name ( if any) is a gridS file name
+      CASE DEFAULT 
+        PRINT *, ' +++ ERROR : Too many files in input !'
+        STOP
+      END SELECT
+    END SELECT
+  ENDDO
 
   IF ( chkfile(cf_tfil) .OR. chkfile(cn_fzgr) .OR. chkfile(cf_sfil)  ) STOP ! missing file
 
@@ -140,6 +158,10 @@ PROGRAM cdfmxl
 
   rdep(1) = 0.
 
+  DO ji = 1, jp_varout
+     stypvar(ji)%ichunk = (/npiglo, MAX(1,npjglo/30), 1, 1 /)
+  ENDDO
+
   ipk(:)                    = 1
   stypvar(1)%cname          = 'somxl010'
   stypvar(2)%cname          = 'somxl030'
@@ -214,8 +236,8 @@ PROGRAM cdfmxl
   ! find W levels for later computation
   nkref10 = MINLOC(gdepw(1:npk),gdepw(1:npk)>=10)-1 ;  IF ( nkref10(1) < 1 ) nkref10(1)=1
 
-  ncout = create      (cf_out, cf_tfil, npiglo, npjglo, 1           )
-  ierr  = createvar   (ncout,  stypvar, pnvarout,      ipk,    id_varout   )
+  ncout = create      (cf_out, cf_tfil, npiglo, npjglo, 1             , ld_nc4=lnc4 )
+  ierr  = createvar   (ncout,  stypvar, jp_varout,      ipk, id_varout, ld_nc4=lnc4 )
   ierr  = putheadervar(ncout,  cf_tfil, npiglo, npjglo, 1, pdep=rdep)
 
   tim  = getvar1d(cf_tfil, cn_vtimec, npt     )
diff --git a/cdfmxlhcsc.f90 b/src/cdfmxlhcsc.f90
similarity index 100%
rename from cdfmxlhcsc.f90
rename to src/cdfmxlhcsc.f90
diff --git a/cdfmxlheatc.f90 b/src/cdfmxlheatc.f90
similarity index 96%
rename from cdfmxlheatc.f90
rename to src/cdfmxlheatc.f90
index 1819584..4c537ab 100644
--- a/cdfmxlheatc.f90
+++ b/src/cdfmxlheatc.f90
@@ -68,6 +68,8 @@ PROGRAM cdfmxlheatc
      PRINT *,'      '
      PRINT *,'     OPTIONS :'
      PRINT *,'       [ -full ] : for full step configurations, default is partial step.' 
+     PRINT *,'       [-o OUT-file ] : specify output file instead of ',TRIM(cf_out)
+     PRINT *,'      '
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'       ',TRIM(cn_fzgr),' and ',TRIM(cn_fmsk) 
@@ -89,6 +91,7 @@ PROGRAM cdfmxlheatc
     CALL getarg (ijarg, cldum   ) ; ijarg = ijarg + 1 
     SELECT CASE ( cldum )
     CASE ( '-full'    ) ; lfull = .true.
+    CASE ( '-o' )     ; CALL getarg (ijarg, cf_out ) ; ijarg = ijarg + 1
     CASE DEFAULT  ; PRINT *, TRIM(cldum),' : unknown option' ; STOP
     END SELECT
   END DO
@@ -143,10 +146,10 @@ PROGRAM cdfmxlheatc
   IF ( lfull ) e31d( :) = getvare3(cn_fzgr, cn_ve3t,  npk)
 
 
-  dvol           = 0.d0
-  dmxlheatc(:,:) = 0.d0
 
   DO jt=1,npt
+     dmxlheatc(:,:) = 0.d0
+     dvol           = 0.d0
      zmxl( :,:) = getvar(cf_tfil, cn_somxl010, 1, npiglo, npjglo, ktime=jt)
      DO jk = 1, npk
         ! Get temperatures at jk
diff --git a/cdfmxlsaltc.f90 b/src/cdfmxlsaltc.f90
similarity index 96%
rename from cdfmxlsaltc.f90
rename to src/cdfmxlsaltc.f90
index 1b839a5..7853af5 100644
--- a/cdfmxlsaltc.f90
+++ b/src/cdfmxlsaltc.f90
@@ -68,7 +68,8 @@ PROGRAM cdfmxlsaltc
      PRINT *,'       T-file : netcdf file with salinity and mixed layer deptht.' 
      PRINT *,'      '
      PRINT *,'     OPTIONS :'
-     PRINT *,'       [-full ] : indicate a full step configuration.' 
+     PRINT *,'       [-full ] : indicate a full step configuration.'
+     PRINT *,'       [-o OUT-file ] : specify output file instead of ',TRIM(cf_out) 
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'       ', TRIM(cn_fzgr),' and ', TRIM(cn_fmsk) 
@@ -90,6 +91,8 @@ PROGRAM cdfmxlsaltc
     SELECT CASE ( cldum )
     CASE ( '-full'    ) ; lfull = .true.
     CASE ( '-partial' ) ; lfull = .false.
+    CASE ('-o') 
+        CALL getarg (ijarg, cf_out) ; ijarg=ijarg+1
     CASE DEFAULT 
       ireq=ireq+1
       SELECT CASE ( ireq )
@@ -148,11 +151,12 @@ PROGRAM cdfmxlsaltc
   IF ( lfull ) e31d( :) = getvare3(cn_fzgr, cn_ve3t,  npk)
 
 
-  dvol           = 0.d0
-  dmxlsaltc(:,:) = 0.d0
 
   DO jt=1,npt
-        zmxl( :,:) = getvar(cf_tfil, cn_somxl010, 1,  npiglo, npjglo, ktime=jt)
+     dvol= 0.d0
+     dmxlsaltc(:,:) = 0.d0
+     zmxl( :,:) = getvar(cf_tfil, cn_somxl010, 1,  npiglo, npjglo, ktime=jt)
+
      DO jk = 1, npk
         zs(   :,:) = getvar(cf_tfil, cn_vosaline, jk, npiglo, npjglo, ktime=jt)
         zmask(:,:) = getvar(cn_fmsk, 'tmask',     jk, npiglo, npjglo          )
@@ -174,17 +178,19 @@ PROGRAM cdfmxlsaltc
         IF (dvol /= 0 )THEN
            !   go on !
         ELSE
-           !   no more layer below !    
+           !   no more layer below !
            EXIT   ! get out of the jk loop
         ENDIF
 
      END DO
 
+
      ! Output to netcdf file : Kg/m2
      dmxlsaltc = rprho0*dmxlsaltc
      ierr = putvar(ncout, id_varout(1), REAL(dmxlsaltc), 1, npiglo, npjglo, ktime=jt)
   END DO
 
+
   ierr = closeout(ncout)
 
 END PROGRAM cdfmxlsaltc
diff --git a/cdfnamelist.f90 b/src/cdfnamelist.f90
similarity index 100%
rename from cdfnamelist.f90
rename to src/cdfnamelist.f90
diff --git a/cdfnan.f90 b/src/cdfnan.f90
similarity index 100%
rename from cdfnan.f90
rename to src/cdfnan.f90
diff --git a/cdfnorth_unfold.f90 b/src/cdfnorth_unfold.f90
similarity index 100%
rename from cdfnorth_unfold.f90
rename to src/cdfnorth_unfold.f90
diff --git a/cdfnrjcomp.f90 b/src/cdfnrjcomp.f90
similarity index 100%
rename from cdfnrjcomp.f90
rename to src/cdfnrjcomp.f90
diff --git a/cdfokubo-w.f90 b/src/cdfokubo-w.f90
similarity index 100%
rename from cdfokubo-w.f90
rename to src/cdfokubo-w.f90
diff --git a/cdfovide.f90 b/src/cdfovide.f90
similarity index 86%
rename from cdfovide.f90
rename to src/cdfovide.f90
index 38f4c8d..c3f09ee 100644
--- a/cdfovide.f90
+++ b/src/cdfovide.f90
@@ -11,6 +11,7 @@ PROGRAM cdfovide
   !!
   !! History : 2.1  : 12/2009  : R. Dussin    : Original code
   !!           3.0  : 01/2011  : J.M. Molines : Doctor norm + Lic.
+  !!           3.1  : 05/2013  : T. Penduff & R. Dussin  : Saving new variables
   !!----------------------------------------------------------------------
   !!----------------------------------------------------------------------
   !!   routines      : description
@@ -35,7 +36,11 @@ PROGRAM cdfovide
   INTEGER(KIND=4) :: nsec=0 ! nb total de points le long de la section
   INTEGER(KIND=4), DIMENSION (:), ALLOCATABLE :: isec, jsec ! indices des points a recuperer
   
-  INTEGER(KIND=4), PARAMETER :: nsta=4
+!	R. Dussin's initial choice 
+!  INTEGER(KIND=4), PARAMETER :: nsta=4
+!	IFREMER (D. Desbruyeres') choice
+  INTEGER(KIND=4), PARAMETER :: nsta=5
+
   INTEGER(KIND=4), DIMENSION(nsta) :: ista, jsta
   INTEGER(KIND=4), DIMENSION(nsta-1) :: ikeepn
 
@@ -70,9 +75,11 @@ PROGRAM cdfovide
   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: lonsec, latsec, dumisec, dumjsec
   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: e1tsec, e1usec, e1vsec, e2tsec, e2usec, e2vsec
   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: e3tsec, e3usec, e3vsec
+  REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: e2join, e3join, dummyvmask
   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: glamu, glamv
   REAL(KIND=4), DIMENSION(:),     ALLOCATABLE :: gdepw
 
+  REAL(KIND=8)                              :: tmp,barot
 
 ! constants
   REAL(KIND=4)   ::  rau0=1000.,  rcp=4000.
@@ -88,7 +95,7 @@ PROGRAM cdfovide
   TYPE (variable), DIMENSION(:), ALLOCATABLE   :: stypvar
   INTEGER(KIND=4)    :: ierr, ncout
   REAL(KIND=4), DIMENSION(1)                    ::  tim
-  INTEGER(KIND=4)    :: nfield=10
+  INTEGER(KIND=4)    :: nfield=14
   INTEGER(KIND=4), DIMENSION(:), ALLOCATABLE :: ipk, id_varout
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
@@ -112,11 +119,20 @@ PROGRAM cdfovide
   lchk = chkfile(cfilev ) .OR. lchk
   IF ( lchk ) STOP ! missing files
 
-  ! Location of leg points that define the 3 legs of OVIDE section
-  rlonsta(1) = -43.00 ; rlatsta(1) = 60.60    ! Greenland
-  rlonsta(2) = -31.30 ; rlatsta(2) = 58.90    ! Reykjanes Ridge
-  rlonsta(3) = -12.65 ; rlatsta(3) = 40.33    ! Off Portugal
-  rlonsta(4) =  -8.70 ; rlatsta(4) = 40.33    ! Lisboa
+  ! R. Dussin : Location of leg points that define the 3 legs of OVIDE section
+  !rlonsta(1) = -43.00 ; rlatsta(1) = 60.60    ! Greenland
+  !rlonsta(2) = -31.30 ; rlatsta(2) = 58.90    ! Reykjanes Ridge
+  !rlonsta(3) = -12.65 ; rlatsta(3) = 40.33    ! Off Portugal
+  !rlonsta(4) =  -8.70 ; rlatsta(4) = 40.33    ! Lisboa
+
+  ! D. Desbruyeres : Location of leg points that define the 4 legs of the OVIDE section
+  rlonsta(1) = -43.70 ; rlatsta(1) = 59.90    ! 
+  rlonsta(2) = -30.30 ; rlatsta(2) = 58.90    ! 
+  rlonsta(3) = -19.40 ; rlatsta(3) = 44.90    ! 
+  rlonsta(4) = -12.65 ; rlatsta(4) = 40.33    ! 
+  rlonsta(5) = -08.70 ; rlatsta(5) = 40.33    ! 
+
+
 
   PRINT *, '###########################################################'
   PRINT *, '#                                                          '
@@ -129,7 +145,7 @@ PROGRAM cdfovide
   PRINT *, '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
 
   !!---------------------------------------------------------------------
-  !!  Find the indexes of the 3 legs (from cdffindij) 
+  !!  Find the indexes of the legs (from cdffindij) 
   !!---------------------------------------------------------------------
 
   npiglo = getdim (cn_fhgr,cn_x)
@@ -169,7 +185,7 @@ PROGRAM cdfovide
   glam0=glam(1, npjglo/2)
   WHERE( glam < glam0 ) glam=glam+360.
 
-  !! loop on the 3 legs
+  !! loop on the legs
   DO k = 1,nsta-1
 
    xmin=rlonsta(k)
@@ -220,8 +236,6 @@ PROGRAM cdfovide
      !      PRINT 9000, 'Long= ',glam(iloc,jloc),' lat = ',gphi(iloc,jloc), iloc, jloc 
   ENDIF
   
-
-
   lagain = .TRUE.
   niter = 0
   !! --- while loop ----------------------------------------------------------------
@@ -389,7 +403,7 @@ PROGRAM cdfovide
   ! compute the number of total points
   ikeepn(k)=nn
   nsec = nsec + nn
-  END DO !! loop on the 3 legs
+  END DO !! loop on the legs
 
 ! fancy control print
 WRITE(*,*) '------------------------------------------------------------'
@@ -404,6 +418,10 @@ WRITE(*,*) '------------------------------------------------------------'
 WRITE(*,9100) 'leg 3 start at ', rlonsta(3) ,'°N ', rlatsta(3), '°W and ends at ', rlonsta(4) ,'°N ', rlatsta(4), '°W'
 WRITE(*,9101) 'corresponding to F-gridpoints(', ista(3),',',jsta(3),') and (', ista(4),',',jsta(4),')' 
 WRITE(*,*) '------------------------------------------------------------'
+WRITE(*,*) '------------------------------------------------------------'
+WRITE(*,9100) 'leg 4 start at ', rlonsta(4) ,'°N ', rlatsta(4), '°W and ends at ', rlonsta(5) ,'°N ', rlatsta(5), '°W'
+WRITE(*,9101) 'corresponding to F-gridpoints(', ista(4),',',jsta(4),') and (', ista(5),',',jsta(5),')' 
+WRITE(*,*) '------------------------------------------------------------'
 
 9100 FORMAT(a,f6.2,a,f6.2,a,f6.2,a,f6.2,a)
 9101 FORMAT(a,i4,a,i4,a,i4,a,i4,a)
@@ -435,9 +453,16 @@ WRITE(*,*) '------------------------------------------------------------'
   ALLOCATE(e1vsec(1,nsec-1), e3vsec(nsec-1,npk) )
   ALLOCATE(ovidetemper(nsec-1,npk), ovidesaline(nsec-1,npk) )
   ALLOCATE(ovidezonalu(nsec-1,npk), ovidemeridv(nsec-1,npk) )
+  ALLOCATE(dummyvmask(nsec-1,npk))
+    
+  
+  e1vsec=-9999.
+  e2usec=-9999.
+  
   
   dumisec(:,:)=0
   dumjsec(:,:)=0
+  
 
   navlon(:,:) = getvar(cfilet, 'nav_lon' ,1,npiglo,npjglo)
   navlat(:,:) = getvar(cfilet, 'nav_lat' ,1,npiglo,npjglo)
@@ -459,30 +484,34 @@ WRITE(*,*) '------------------------------------------------------------'
 
   END DO
 
-  DO iloop=1,nsec-1
+	jk=1
 
+  DO iloop=1,nsec-1
+	 !PRINT*, 'iloop=', iloop
+	
   IF ( jsec(iloop+1) == jsec(iloop) ) THEN ! horizontal segment
     IF ( isec(iloop+1) > isec(iloop) ) THEN ! eastward
 
-       e2usec(iloop,jk) = 0.
-       e1vsec(iloop,jk) = e1v(isec(iloop)+1,jsec(iloop))
+       e2usec(jk,iloop) = 0.
+       e1vsec(jk,iloop) = e1v(isec(iloop)+1,jsec(iloop))
 
     ELSE
 
-       e2usec(iloop,jk) = 0.
-       e1vsec(iloop,jk) = e1v(isec(iloop),jsec(iloop))
+       e2usec(jk,iloop) = 0.
+       e1vsec(jk,iloop) = e1v(isec(iloop),jsec(iloop))
 
     ENDIF
   ELSEIF ( isec(iloop+1) == isec(iloop) ) THEN ! vertical segment
     IF ( jsec(iloop+1) < jsec(iloop) ) THEN ! southward
 
-       e2usec(iloop,jk) = e2u(isec(iloop),jsec(iloop))
-       e1vsec(iloop,jk) = 0.
+       e2usec(jk,iloop) = e2u(isec(iloop),jsec(iloop))
+       e1vsec(jk,iloop) = 0.
 
     ELSE
 
-       e2usec(iloop,jk) = e2u(isec(iloop),jsec(iloop)+1)
-       e1vsec(iloop,jk) = 0.
+       e2usec(jk,iloop) = e2u(isec(iloop),jsec(iloop)+1)
+       e1vsec(jk,iloop) = 0.
+
     ENDIF
   ELSE
        PRINT *, 'problem'
@@ -490,6 +519,11 @@ WRITE(*,*) '------------------------------------------------------------'
   ENDIF
   END DO
 
+!	PRINT*,nsec
+!	PRINT*, MINVAL(e1v),MAXVAL(e1v),MINVAL(e2u),MAXVAL(e2u)  
+!	PRINT*, MINVAL(e1vsec),MAXVAL(e1vsec),MINVAL(e2usec),MAXVAL(e2usec)  
+!	PAUSE		
+	
   ! loop on 3d arrays
   DO jk=1,npk
   temper(:,:) = getvar(cfilet, 'votemper',jk,npiglo,npjglo)
@@ -565,6 +599,7 @@ WRITE(*,*) '------------------------------------------------------------'
   END DO
   END DO
 
+
   ALLOCATE ( stypvar(nfield), ipk(nfield), id_varout(nfield) )
 
   DO iloop=1,nfield
@@ -583,7 +618,7 @@ WRITE(*,*) '------------------------------------------------------------'
   stypvar(1)%clong_name='Temperature along OVIDE section'
   stypvar(1)%cshort_name='votemper'
   stypvar%conline_operation='N/A'
-  stypvar%caxis='TYZ'
+  stypvar%caxis='TXZ'
 
   stypvar(2)%cname= 'vosaline'
   stypvar(2)%cunits='PSU'
@@ -592,14 +627,14 @@ WRITE(*,*) '------------------------------------------------------------'
   stypvar(2)%clong_name='Salinity along OVIDE section'
   stypvar(2)%cshort_name='vosaline'
 
-  stypvar(3)%cname= 'vozocrtx'
+  stypvar(3)%cname= 'vozocrtx_native'
   stypvar(3)%cunits='m.s-1'
   stypvar(3)%valid_min= -20.
   stypvar(3)%valid_max= 20.
   stypvar(3)%clong_name='Zonal velocity along OVIDE section'
   stypvar(3)%cshort_name='vozocrtx'
 
-  stypvar(4)%cname= 'vomecrty'
+  stypvar(4)%cname= 'vomecrty_native'
   stypvar(4)%cunits='m.s-1'
   stypvar(4)%valid_min= -20.
   stypvar(4)%valid_max= 20.
@@ -612,38 +647,99 @@ WRITE(*,*) '------------------------------------------------------------'
   stypvar(6)%cname= 'jsec'
   stypvar(6)%valid_min= 0.
   stypvar(6)%valid_max= npjglo 
-  stypvar(7)%cname= 'e2u'
+  stypvar(7)%cname= 'e2u_native'
   stypvar(7)%valid_min= MINVAL(e2usec(1,:))
   stypvar(7)%valid_max= MAXVAL(e2usec(1,:)) 
-  stypvar(8)%cname= 'e1v'
+  stypvar(8)%cname= 'e1v_native'
   stypvar(8)%valid_min= MINVAL(e1vsec(1,:))
   stypvar(8)%valid_max= MAXVAL(e1vsec(1,:))
-  stypvar(9)%cname= 'e3u'
+  stypvar(9)%cname= 'e3u_native'
   stypvar(9)%valid_min= MINVAL(e3usec(:,:))
   stypvar(9)%valid_max= MAXVAL(e3usec(:,:)) 
-  stypvar(10)%cname= 'e3v'
+  stypvar(10)%cname= 'e3v_native'
   stypvar(10)%valid_min= MINVAL(e3vsec(:,:))
   stypvar(10)%valid_max= MAXVAL(e3vsec(:,:)) 
 
+  stypvar(11)%cname= 'vomecrty'
+  stypvar(11)%cunits='m.s-1'
+  stypvar(11)%valid_min= -20.
+  stypvar(11)%valid_max= 20.
+  stypvar(11)%clong_name='Normal velocity along OVIDE section'
+  stypvar(11)%cshort_name='vomecrty'
+
+  stypvar(12)%cname= 'e1v'
+  stypvar(12)%cunits='m'
+  stypvar(12)%valid_min= 0.
+  stypvar(12)%valid_max= 1000000.
+  stypvar(12)%clong_name='Local horiz. resolution along OVIDE section'
+  stypvar(12)%cshort_name='e1v'
+
+  stypvar(13)%cname= 'e3v_ps'
+  stypvar(13)%cunits='m'
+  stypvar(13)%valid_min= 0.
+  stypvar(13)%valid_max= 100000000.
+  stypvar(13)%clong_name='Local vert. resolution along OVIDE section'
+  stypvar(13)%cshort_name='e3v_ps'
+
+  stypvar(14)%cname= 'vmask'
+  stypvar(12)%cunits=''
+  stypvar(12)%valid_min= 0.
+  stypvar(12)%valid_max= 1.
+  stypvar(12)%clong_name='Mask along OVIDE section'
+  stypvar(12)%cshort_name='vmask'
+
   ! create output fileset
-   ncout =create(cfileoutnc, 'none', 1,nsec,npk,cdep='depthw')
+   ncout =create(cfileoutnc, 'none', nsec,1, npk,cdep='depthw')
    ierr= createvar(ncout ,stypvar,nfield, ipk,id_varout )
-   ierr= putheadervar(ncout, cfilet,1, nsec,npk,pnavlon=lonsec,pnavlat=latsec,pdep=gdepw)
+   ierr= putheadervar(ncout, cfilet,nsec,1, npk,pnavlon=lonsec,pnavlat=latsec,pdep=gdepw)
    tim=getvar1d(cfilet,'time_counter',1)
    ierr=putvar1d(ncout,tim,1,'T')
 
+
+  dummyvmask(:,:) = 1.
+  WHERE( ovidesaline(:,:) == 0. ) dummyvmask(:,:) = 0.
+
+
+	!PRINT*, MINVAL(e1v),MAXVAL(e1v),MINVAL(e2u),MAXVAL(e2u)  
+	!PRINT*, MINVAL(e1vsec),MAXVAL(e1vsec),MINVAL(e2usec),MAXVAL(e2usec)  
+	!PAUSE
+
+!------------------- BAROTROPIC TRANSPORT
+    barot = 0.
+    
+  DO iloop=1,nsec-1
+  DO jk=1,npk
+	tmp=(ovidezonalu(iloop,jk)+ovidemeridv(iloop,jk))*&
+	    (e2usec(1,iloop)+e1vsec(1,iloop))*&
+	    (e3usec(iloop,jk)+e3vsec(iloop,jk))*&
+	    dummyvmask(iloop,jk)
+    barot=barot+tmp
+  ENDDO
+	    !jk=1
+		!PRINT*,iloop,(ovidezonalu(iloop,jk)+ovidemeridv(iloop,jk)),(e2usec(1,iloop)+e1vsec(1,iloop)),&
+		!(e3usec(iloop,jk)+e3vsec(iloop,jk)),dummyvmask(iloop,jk),barot
+  ENDDO
+	PRINT*, 'BAROTROPIC TRANSPORT = ', barot/1.e6, ' Sv.'
+!--------------------------------------------
+
+
   ! netcdf output 
     DO jk =1, npk
-    ierr = putvar (ncout, id_varout(1), REAL(ovidetemper(:,jk)), jk,1,nsec-1)
-    ierr = putvar (ncout, id_varout(2), REAL(ovidesaline(:,jk)), jk,1,nsec-1)
-    ierr = putvar (ncout, id_varout(3), REAL(ovidezonalu(:,jk)), jk,1,nsec-1)
-    ierr = putvar (ncout, id_varout(4), REAL(ovidemeridv(:,jk)), jk,1,nsec-1)
+    ierr = putvar (ncout, id_varout(1), REAL(ovidetemper(:,jk)), jk,nsec-1,1)
+    ierr = putvar (ncout, id_varout(2), REAL(ovidesaline(:,jk)), jk,nsec-1,1)
+    ierr = putvar (ncout, id_varout(3), REAL(ovidezonalu(:,jk)), jk,nsec-1,1)
+    ierr = putvar (ncout, id_varout(4), REAL(ovidemeridv(:,jk)), jk,nsec-1,1)
     ierr = putvar (ncout, id_varout(5), REAL(dumisec(1,:)), jk,1,nsec)
     ierr = putvar (ncout, id_varout(6), REAL(dumjsec(1,:)), jk,1,nsec)
-    ierr = putvar (ncout, id_varout(7),REAL(e2usec(1,:)), jk,1,nsec-1)
-    ierr = putvar (ncout, id_varout(8),REAL(e1vsec(1,:)), jk,1,nsec-1)
-    ierr = putvar (ncout, id_varout(9),REAL(e3usec(:,jk)), jk,1,nsec-1)
-    ierr = putvar (ncout, id_varout(10),REAL(e3vsec(:,jk)), jk,1,nsec-1)
+    ierr = putvar (ncout, id_varout(7), REAL(e2usec(1,:)), jk,nsec-1,1)
+    ierr = putvar (ncout, id_varout(8), REAL(e1vsec(1,:)), jk,nsec-1,1)
+    ierr = putvar (ncout, id_varout(9), REAL(e3usec(:,jk)), jk,nsec-1,1)
+    ierr = putvar (ncout, id_varout(10),REAL(e3vsec(:,jk)), jk,nsec-1,1)
+  ! along-track normal velocity, horiz. and vert. resolution, and mask
+    ierr = putvar (ncout, id_varout(11),REAL(ovidezonalu(:,jk) + ovidemeridv(:,jk)), jk,nsec-1,1)
+    ierr = putvar (ncout, id_varout(12),REAL(e2usec(1,:) + e1vsec(1,:)), jk,nsec-1,1)
+    ierr = putvar (ncout, id_varout(13),REAL(e3usec(:,jk) + e3vsec(:,jk)), jk,nsec-1,1)
+    ierr = putvar (ncout, id_varout(14),REAL(dummyvmask(:,jk)), jk,nsec-1,1)
     END DO
 
   ierr = closeout(ncout)
diff --git a/src/cdfpdf.f90 b/src/cdfpdf.f90
new file mode 100644
index 0000000..39d0c53
--- /dev/null
+++ b/src/cdfpdf.f90
@@ -0,0 +1,262 @@
+PROGRAM cdfpdf
+  !!======================================================================
+  !!                     ***  PROGRAM  cdfpdf  ***
+  !!=====================================================================
+  !!  ** Purpose : Build the pdf for a given variable on a given area.
+  !!
+  !!  ** Method  : Establish a data binning and count the number of element
+  !!               in each bin.  Binning is defined from given  minimum 
+  !!               value, maximum value, and number of bins
+  !!
+  !! History : 3.0  : 10/2015  : J.M. Molines : Original code
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE modcdfnames
+  USE modutils
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2015
+  !! $Id$
+  !! Copyright (c) 2015, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)                           :: ji, jj, jk, jt
+  INTEGER(KIND=4)                           :: npiglo, npjglo            ! size of the domain
+  INTEGER(KIND=4)                           :: npk, npt                  ! size of the domain
+  INTEGER(KIND=4)                           :: npi, npj, ilev            !
+  INTEGER(KIND=4)                           :: narg, iargc, ijarg
+  INTEGER(KIND=4)                           :: numout=10
+  INTEGER(KIND=4)                           :: imin, imax 
+  INTEGER(KIND=4)                           :: jmin, jmax
+  INTEGER(KIND=4)                           :: nbin, nlim, ibin
+  INTEGER(KIND=4)                           :: ncout             ! ncid of output variable
+  INTEGER(KIND=4)                           :: ierr              ! error status
+  INTEGER(KIND=4), DIMENSION(1)             :: ipk , id_varout   ! output variable
+
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zvar, zcount, ztimed, zlon
+  REAL(KIND=4), DIMENSION(:)  , ALLOCATABLE :: vlim, ztimes
+  REAL(KIND=4)                              :: vmin, vmax, bin_siz
+  REAL(KIND=4)                              :: below, above, spval
+
+  CHARACTER(LEN=256)                        :: cf_ifil
+  CHARACTER(LEN=256)                        :: cf_asc='pdf.txt'
+  CHARACTER(LEN=256)                        :: cf_out='pdf.nc'
+  CHARACTER(LEN=256)                        :: cv_nam
+  CHARACTER(LEN=256)                        :: cldum
+  CHARACTER(LEN=256)                        :: cglobal
+
+  TYPE(variable), DIMENSION(1)              :: stypvar           ! output data structure
+
+  LOGICAL                                   :: lchk
+  LOGICAL                                   :: l_nozoom=.true.
+  LOGICAL                                   :: l_norange=.true.
+  !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  narg = iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage :  cdfpdf -f IN-file -v IN-var [-zoom imin imax jmin jmax] ..'
+     PRINT *,'       [-lev level ] [-range vmin vmax nbin ] [-o OUT-ncfile] [-a OUT-ascfile]'
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'       Build the pdf of a given variable, on a given area, according'
+     PRINT *,'       to bin specifications passed as argument of the program. If no' 
+     PRINT *,'       particular specification is passed to the program, build 100 '
+     PRINT *,'       bins between minimum and maximum value of the variable.'
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       -f IN-file : input file '
+     PRINT *,'       -v IN-var  : variable name '
+     PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'       [-zoom imin imax jmin jmax] : define a sub-area, in model '
+     PRINT *,'                                     coordinates' 
+     PRINT *,'       [ -lev level ] : choose a level for pdf computation '
+     PRINT *,'              If not specified, takes level 1 '
+     PRINT *,'       [-range vmin vmax nbin  ] : define the limit for binning '
+     PRINT *,'                               and number of bins.'
+     PRINT *,'       [-o OUT-file] : specify name for netcdf output file'
+     PRINT *,'       [-a ASC-file] : specify name for ascii output file'
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'          (1) ascii file with bin number, value and mean field in bin'
+     PRINT *,'          (2) netcdf file for 2d array where x dimension corresponds to bins'
+     PRINT *,'              y dimension corresponds to time, thus the field value being '
+     PRINT *,'              an array count(bin,time). The output file follows the nemo '
+     PRINT *,'              standards, even, if nav_lon, nav_lat are no more longitude or'
+     PRINT *,'              latitude.'
+     PRINT *,'              netdf variable is <IN-var>_pdf'
+     PRINT *,'      '
+     PRINT *,'     SEE ALSO : '
+     STOP
+  ENDIF
+
+  ijarg = 1
+  ilev  = 1
+  l_nozoom = .true.
+  DO WHILE ( ijarg <= narg )
+     CALL getarg(ijarg, cldum ) ; ijarg=ijarg+1
+     SELECT CASE ( cldum )
+     CASE ( '-f'   ) ; CALL getarg(ijarg, cf_ifil) ; ijarg=ijarg+1
+     CASE ( '-o'   ) ; CALL getarg(ijarg, cf_out ) ; ijarg=ijarg+1
+     CASE ( '-a'   ) ; CALL getarg(ijarg, cf_asc ) ; ijarg=ijarg+1
+     CASE ( '-v'   ) ; CALL getarg(ijarg, cv_nam ) ; ijarg=ijarg+1
+     CASE ( '-zoom') ; l_nozoom = .false.
+             CALL getarg(ijarg, cldum ) ; ijarg=ijarg+1 ; READ(cldum,*) imin
+             CALL getarg(ijarg, cldum ) ; ijarg=ijarg+1 ; READ(cldum,*) imax
+             CALL getarg(ijarg, cldum ) ; ijarg=ijarg+1 ; READ(cldum,*) jmin
+             CALL getarg(ijarg, cldum ) ; ijarg=ijarg+1 ; READ(cldum,*) jmax
+     CASE ( '-lev') 
+             CALL getarg(ijarg, cldum ) ; ijarg=ijarg+1 ; READ(cldum,*) ilev
+     CASE ( '-range') ; l_norange = .false.
+             CALL getarg(ijarg, cldum ) ; ijarg=ijarg+1 ; READ(cldum,*) vmin
+             CALL getarg(ijarg, cldum ) ; ijarg=ijarg+1 ; READ(cldum,*) vmax
+             CALL getarg(ijarg, cldum ) ; ijarg=ijarg+1 ; READ(cldum,*) nbin
+     CASE DEFAULT
+             PRINT *,' option ',TRIM(cldum),' not understood'
+     END SELECT
+  ENDDO
+
+  IF (  chkfile ( cf_ifil) ) STOP  ! some compulsory files are missing
+
+  ! set domain size from input ile
+  npiglo = getdim (cf_ifil,cn_x)
+  npjglo = getdim (cf_ifil,cn_y)
+  npk    = getdim (cf_ifil,cn_z)
+  npt    = getdim (cf_ifil,cn_t)
+
+  PRINT *, 'npiglo =', npiglo
+  PRINT *, 'npjglo =', npjglo
+  PRINT *, 'npk    =', npk
+  PRINT *, 'npt    =', npt
+  
+  ! if no zoom specified, take the full domain
+  IF ( l_nozoom ) THEN
+    imin=1 ; imax=npiglo
+    jmin=1 ; jmax=npjglo
+  ENDIF
+
+  npi=imax - imin + 1
+  npj=jmax - jmin + 1
+  ALLOCATE ( zvar(npi,npj) )
+
+  ! takle the case when no range specified for binning
+  IF ( l_norange ) THEN
+    nbin =100
+    spval = getspval( cf_ifil, cv_nam) 
+    ! scan the file for min and max
+     vmin=1.e10
+     vmax=-1.e10
+    DO jt=1,npt
+      zvar(:,:) = getvar( cf_ifil, cv_nam, ilev, npi, npj, ktime=jt, kimin=imin, kjmin=jmin )
+      zvar(:,:) = getvar( cf_ifil, cv_nam, ilev, npi, npj,  ktime=jt, kimin=imin, kjmin=jmin )
+      vmin=MIN(vmin, MINVAL(zvar, (zvar /= spval) ) )
+      vmax=MAX(vmax, MAXVAL(zvar, (zvar /= spval) ) )
+    ENDDO
+  ENDIF
+
+  bin_siz=(vmax - vmin ) / nbin
+  nlim = nbin+1
+
+  PRINT *, ' NPI  = ', npi
+  PRINT *, ' NPJ  = ', npj
+  PRINT *, ' IMIN = ', imin
+  PRINT *, ' IMAX = ', imax
+  PRINT *, ' JMIN = ', jmin
+  PRINT *, ' JMAX = ', jmax
+  PRINT *, ' ILEV = ', ilev
+  PRINT *, ' VMIN = ', vmin
+  PRINT *, ' VMAX = ', vmax
+  PRINT *, ' NBIN = ', nbin
+  PRINT *, ' NLIM = ', nlim
+  PRINT *, ' BINS = ', bin_siz
+
+
+  ! Allocate memory
+  ALLOCATE ( zcount(nbin,npt), vlim(nlim) )
+  ALLOCATE ( ztimes(npt), ztimed(nbin,npt) , zlon(nbin,npt))
+
+  DO ji=1, nlim 
+     vlim(ji)= vmin + (ji-1)*bin_siz
+  ENDDO
+
+  OPEN (numout, FILE=cf_asc)   ! this file can be plotted easily with graph
+  ! time in seconds read from file 
+  ztimes  = getvar1d(cf_ifil, cn_vtimec, npt )
+
+  ! convert in time in days since the begining of the file
+  ! this will be the dummy 'latitude' for the output file
+ 
+  DO jt=1, npt
+    ztimed(:,jt) = (ztimes(jt) - ztimes(1) ) / 86400.
+  ENDDO
+
+ ! dummy longitude for the output file in the mean value of the bin
+  DO ji = 1, nbin
+    zlon(ji,:) =  (vlim(ji) + vlim(ji+1)) /2.
+  ENDDO
+
+  CALL CreateOutput 
+
+  DO jt = 1, npt
+      zcount(:,jt) = 0. ; below=0. ; above=0.
+      zvar(:,:) = getvar( cf_ifil, cv_nam, ilev, npi, npj,  ktime=jt, kimin=imin, kjmin=jmin )
+      DO jj=1,npj
+        DO ji=1,npi
+           ibin=INT((zvar(ji,jj)-vmin)/bin_siz) +1
+           IF ( ibin < 1 ) THEN 
+              below=below+1
+           ELSE IF ( ibin > nbin ) THEN
+              above=above+1
+           ELSE
+              zcount(ibin,jt) = zcount(ibin,jt) + 1
+           ENDIF
+        ENDDO
+      ENDDO
+
+      WRITE(numout,*) 
+      WRITE(numout,*) vlim(1),  below
+      DO ji=1, nbin
+         WRITE(numout,*)  (vlim(ji) + vlim(ji+1)) /2.,  zcount (ji,jt )
+      ENDDO
+      WRITE(numout,*)  vlim(nlim),  above
+  ENDDO
+   ierr = putvar( ncout, id_varout(1), zcount, 1, nbin, npt)
+   ierr = closeout(ncout)
+  CLOSE(numout)
+
+CONTAINS
+  SUBROUTINE CreateOutput
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE CreateOutput  ***
+      !!
+      !! ** Purpose :  Set up all things required for the output file, create
+      !!               the file and write the header part. 
+      !!
+      !! ** Method  :  Use global module variables 
+      !!
+      !!----------------------------------------------------------------------
+      ipk(:) = 1
+
+      stypvar(1)%cname             = 'pdf_'//TRIM(cv_nam)
+      stypvar(1)%cunits            = 'N/A'
+      stypvar(1)%rmissing_value    = -1000.
+      stypvar(1)%valid_min         = 0.
+      stypvar(1)%valid_max         = npi*npj
+      stypvar(1)%clong_name        = 'PDF of '//TRIM(cv_nam)
+      stypvar(1)%cshort_name       = 'pdf_'//TRIM(cv_nam)
+      stypvar(1)%conline_operation = 'N/A'
+
+      CALL SetGlobalAtt (cglobal)
+
+      ! create output fileset
+      ncout = create      (cf_out, 'none', nbin, npt, 0      )
+      ierr  = createvar   (ncout,  stypvar, 1, ipk, id_varout , cdglobal=cglobal        )
+      ierr  = putheadervar(ncout,  cf_ifil, nbin, npt, 0 , pnavlon=zlon, pnavlat=ztimed )
+      
+
+  END SUBROUTINE CreateOutput
+END PROGRAM cdfpdf
diff --git a/cdfpendep.f90 b/src/cdfpendep.f90
similarity index 100%
rename from cdfpendep.f90
rename to src/cdfpendep.f90
diff --git a/cdfpolymask.f90 b/src/cdfpolymask.f90
similarity index 88%
rename from cdfpolymask.f90
rename to src/cdfpolymask.f90
index e6f3d06..d619b32 100644
--- a/cdfpolymask.f90
+++ b/src/cdfpolymask.f90
@@ -50,7 +50,7 @@ PROGRAM cdfpolymask
 
   narg = iargc()
   IF ( narg < 2 ) THEN
-     PRINT *,' usage : cdfpolymask POLY-file REF-file [ -r]'
+     PRINT *,' usage : cdfpolymask -p POLY-file -ref REF-file [ -r] [-o OUT_file]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
      PRINT *,'       Create a maskfile with polymask variable having 1'
@@ -58,18 +58,22 @@ PROGRAM cdfpolymask
      PRINT *,'       the behaviour (0 inside, 1 outside).'
      PRINT *,'      '
      PRINT *,'     ARGUMENTS :'
-     PRINT *,'       POLY-file : input ASCII file describing a polyline in I J grid.'
+     PRINT *,'       -p POLY-file : input ASCII file describing a polyline in I J grid.'
      PRINT *,'            This file is structured by block, one block corresponding '
      PRINT *,'            to a polygon:'
      PRINT *,'              1rst line of the block gives a polygon name'
      PRINT *,'              2nd line gives the number of vertices (nvert) and a dummy 0'
      PRINT *,'              the block finishes  with nvert pairs of (I,J) describing '
      PRINT *,'              the polygon vertices.'
-     PRINT *,'       REF-file  : reference netcdf file for header of polymask file.'
+     PRINT *,'       -ref REF-file  : reference netcdf file for header of polymask file.'
+     PRINT *,'             This file will be used to look for domain dimensions, and '
+     PRINT *,'             in order to build the output file (nav_lon, nav_lat etc ...)'
      PRINT *,'      '
      PRINT *,'     OPTIONS :'
      PRINT *,'        [ -r ] : revert option. When used, 0 is inside the polygon,'
      PRINT *,'                 1 outside.'
+     PRINT *,'        [ -o OUT-file ] : spefify the name of the output mask file instead'
+     PRINT *,'                 of ',TRIM(cf_out)
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'       none' 
@@ -81,16 +85,16 @@ PROGRAM cdfpolymask
   ENDIF
 
   ijarg = 1 
-  CALL getarg (ijarg, cf_poly) ; ijarg = ijarg + 1
-  CALL getarg (ijarg, cf_ref ) ; ijarg = ijarg + 1
 
   DO WHILE ( ijarg <= narg ) 
      CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1
      SELECT CASE ( cldum ) 
-     CASE ( '-r' ) ; lreverse = .TRUE.
+     CASE ( '-p'   ) ; CALL getarg (ijarg, cf_poly ) ; ijarg = ijarg + 1
+     CASE ( '-ref' ) ; CALL getarg (ijarg, cf_ref  ) ; ijarg = ijarg + 1
+     CASE ( '-o'   ) ; CALL getarg (ijarg, cf_out  ) ; ijarg = ijarg + 1
+     CASE ( '-r'   ) ; lreverse = .TRUE.
      CASE DEFAULT
-        PRINT *,' unknown optional arugment (', TRIM(cldum),' )'
-        PRINT *,' in actual version only -r -- for reverse -- is recognized '
+        PRINT *,' unknown optional argument (', TRIM(cldum),' )'
         STOP
      END SELECT
   END DO
diff --git a/cdfprobe.f90 b/src/cdfprobe.f90
similarity index 100%
rename from cdfprobe.f90
rename to src/cdfprobe.f90
diff --git a/cdfprofile.f90 b/src/cdfprofile.f90
similarity index 100%
rename from cdfprofile.f90
rename to src/cdfprofile.f90
diff --git a/cdfpsi.f90 b/src/cdfpsi.f90
similarity index 96%
rename from cdfpsi.f90
rename to src/cdfpsi.f90
index a634def..fccda2b 100644
--- a/cdfpsi.f90
+++ b/src/cdfpsi.f90
@@ -80,13 +80,14 @@ PROGRAM cdfpsi
   LOGICAL                                   :: lmean = .FALSE. ! flag for mean U,V calculation
   LOGICAL                                   :: lopen = .FALSE. ! flag for open calculation
   LOGICAL                                   :: lssh  = .FALSE. ! flag for ssh computation
+  LOGICAL                                   :: lnc4  = .FALSE. ! flag for netcdf4 cchunking and deflation
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
   narg= iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfpsi U-file V-file [V] [-full ] [-mask ] [-mean] ...'
-     PRINT *,'          ... [-ssh T-file ] [-open ] [-ref iref jref ]'
+     PRINT *,' usage : cdfpsi U-file V-file [V] [-full ] [-mask ] [-mean] [-nc4 ] ...'
+     PRINT *,'          ... [-ssh T-file ] [-open ] [-ref iref jref ] [-o OUT-file]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
      PRINT *,'       Computes the barotropic stream function (a proxy ) as the integral of '
@@ -102,6 +103,7 @@ PROGRAM cdfpsi
      PRINT *,'       [ -mask ] : mask output fields. Note that the land value is significant.'
      PRINT *,'                   It correspond to the potential on this continent.'
      PRINT *,'       [ -mean ] : save the average of the computations done with U and V.'
+     PRINT *,'       [ -nc4  ] : use netcdf4 output files with chunking and deflation'
      PRINT *,'       [ -ssh T-file ] : compute the transport in the ''ssh'' layer, using '
      PRINT *,'                  surface velocities. Take the ssh from T-file specified in '
      PRINT *,'                  this option. This is a experimental option, not certified ...'
@@ -109,6 +111,7 @@ PROGRAM cdfpsi
      PRINT *,'                   reference point.'
      PRINT *,'       [ -ref iref jref ] : Set the reference point in i,j coordinates.'
      PRINT *,'                   BSF at reference point is arbitrarly set to zero.'
+     PRINT *,'       [ -o  OUT-file ] : specify output file name instead of default ',TRIM(cf_out)
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'       ', TRIM(cn_fhgr),' and ', TRIM(cn_fzgr),'.'
@@ -136,7 +139,9 @@ PROGRAM cdfpsi
      CASE ('-mean') ; lmean = .TRUE.  ; ll_v=.TRUE. ; ll_u=.TRUE.
      CASE ('-ssh' ) ; lssh  = .TRUE.  ; nvout=3
         CALL getarg( ijarg, cf_tfil ) ; ijarg=ijarg + 1 
+     CASE ('-nc4' ) ; lnc4  = .TRUE. 
      CASE ('-open') ; lopen = .TRUE.  ; ll_v=.TRUE. ; ll_u=.TRUE.
+     CASE ('-o'   ) ; CALL getarg( ijarg, cf_out )   ; ijarg=ijarg + 1 
      CASE ('-ref') 
         CALL getarg( ijarg, cldum )   ; ijarg=ijarg + 1 ; READ(cldum,*) iiref
         CALL getarg( ijarg, cldum )   ; ijarg=ijarg + 1 ; READ(cldum,*) ijref
@@ -180,6 +185,9 @@ PROGRAM cdfpsi
   stypvar(:)%valid_max         = 300.e6
   stypvar(:)%conline_operation = 'N/A'
   stypvar(:)%caxis             = 'TYX'
+  DO ji=1,nvout
+    stypvar(ji)%ichunk = (/npiglo,MAX(1,npjglo/30),1,1 /)
+  ENDDO
 
   stypvar(1)%cname             = cv_out
   stypvar(1)%rmissing_value    = 0.
@@ -229,8 +237,8 @@ PROGRAM cdfpsi
   gphif(:,:) = getvar(cn_fhgr, cn_gphif, 1, npiglo, npjglo)
 
   ! create output fileset
-  ncout = create      (cf_out, cf_ufil, npiglo, npjglo, 1              )
-  ierr  = createvar   (ncout,  stypvar, nvout,  ipk,    id_varout, cdglobal=TRIM(cglobal)      )
+  ncout = create      (cf_out, cf_ufil, npiglo, npjglo, 1                                , ld_nc4=lnc4 )
+  ierr  = createvar   (ncout,  stypvar, nvout,  ipk,    id_varout, cdglobal=TRIM(cglobal), ld_nc4=lnc4 )
   ierr  = putheadervar(ncout,  cf_ufil, npiglo, npjglo, 1, glamf, gphif)
 
   tim  = getvar1d(cf_ufil, cn_vtimec, npt     )
diff --git a/cdfpsi_level.f90 b/src/cdfpsi_level.f90
similarity index 100%
rename from cdfpsi_level.f90
rename to src/cdfpsi_level.f90
diff --git a/cdfpvor.f90 b/src/cdfpvor.f90
similarity index 92%
rename from cdfpvor.f90
rename to src/cdfpvor.f90
index 4cc2186..49ee05a 100644
--- a/cdfpvor.f90
+++ b/src/cdfpvor.f90
@@ -24,7 +24,7 @@ PROGRAM cdfpvor
   !!        units : U, V in m.s-1
   !!           e1u, e2v, e1f, e2f in m
   !!           f, xsi in s-1
-  !!           Qpot, Qrel, Qstr in kg.m-4.s-1
+  !!           Qpot, Qrel, Qstr in 1.e-7 kg.m-4.s-1
   !!
   !! History : 2.1  : 12/2005  : A.M. Treguier : Original code
   !!           3.0  : 05/2011  : J.M. Molines  : Doctor norm + Lic., merge with cdfpv
@@ -80,12 +80,13 @@ PROGRAM cdfpvor
   LOGICAL                                     :: lfull  = .FALSE.     ! flag for full step
   LOGICAL                                     :: lertel = .TRUE.      ! flag for large scale pv
   LOGICAL                                     :: lchk   = .FALSE.     ! flag for missing files
+  LOGICAL                                     :: lnc4   = .FALSE.     ! flag for netcdf4 chunking and deflation
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
   narg= iargc()
   IF ( narg < 2 ) THEN
-     PRINT *,' usage : cdfpvor T-file  U-file V-file [-full] [-lspv ]'
+     PRINT *,' usage : cdfpvor T-file  U-file V-file [-full] [-lspv ] [-nc4] [-o output file]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
      PRINT *,'       Compute the Ertel potential vorticity and save the relative  ' 
@@ -103,20 +104,22 @@ PROGRAM cdfpvor
      PRINT *,'       [-lspv ] : calculate only the large scale potential vorticity.'
      PRINT *,'                  ( replace the old cdflspv tool).'
      PRINT *,'                  If used only T-file is required, no need for velocities.'
+     PRINT *,'       [-nc4 ] :  use netcdf4 with chunking and deflation '
+     PRINT *,'       [-o output file ] : use output file instead of default ',TRIM(cf_out)
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'       ', TRIM(cn_fhgr),' and ',TRIM(cn_fzgr)
      PRINT *,'      '
      PRINT *,'     OUTPUT : '
      PRINT *,'       netcdf file : ', TRIM(cf_out) 
-     PRINT *,'         variables : vorelvor (kg.m-4.s-1 ) relative vorticity'
-     PRINT *,'                     vostrvor (kg.m-4.s-1 ) stretching vorticity'
-     PRINT *,'                     vototvor (kg.m-4.s-1 ) total potential vorticity'
+     PRINT *,'         variables : vorelvor (1.e-7 kg.m-4.s-1 ) relative vorticity'
+     PRINT *,'                     vostrvor (1.e-7 kg.m-4.s-1 ) stretching vorticity'
+     PRINT *,'                     vototvor (1.e-7 kg.m-4.s-1 ) total potential vorticity'
      PRINT *,'                  Ertel PV are located at T points.'
      PRINT *,'           '
      PRINT *,'       With option -lspv :'
      PRINT *,'       netcdf file : lspv.nc'
-     PRINT *,'         variables :  volspv  (kg.m-4.s-1 ) large scale potential vorticity'
+     PRINT *,'         variables :  volspv  (1.e-7 kg.m-4.s-1 ) large scale potential vorticity'
      PRINT *,'                  LSPV is  located at W points.'
      PRINT *,'      '
      PRINT *,'     SEE ALSO :'
@@ -132,6 +135,8 @@ PROGRAM cdfpvor
      SELECT CASE ( cldum )
      CASE ( '-full' ) ; lfull  = .TRUE.
      CASE ( '-lspv' ) ; lertel = .FALSE. ; nvar = 1 ; cf_out = 'lspv.nc'
+     CASE ( '-nc4'  ) ; lnc4 = .TRUE.
+     CASE ( '-o'    ) ; CALL getarg( ijarg, cf_out ) ; ijarg = ijarg + 1
      CASE DEFAULT
         ireq=ireq+1
         SELECT CASE ( ireq )
@@ -187,7 +192,10 @@ PROGRAM cdfpvor
   zpi         = ACOS(-1.)
   zomega      = 2.0  * zpi /(3600*24)
   d2fcor(:,:) = 2.d0 * zomega * SIN(gphit(:,:)*zpi/180.0)
-  dareat(:,:) = 4.d0 * e1t(:,:) * e2t(:,:)  ! factor of 4 to normalize relative vorticity
+
+  IF ( lertel ) THEN
+    dareat(:,:) = 4.d0 * e1t(:,:) * e2t(:,:)  ! factor of 4 to normalize relative vorticity
+  ENDIF
 
   gdepw(:) = getvare3(cn_fzgr, cn_gdepw, npk)
 
@@ -199,13 +207,17 @@ PROGRAM cdfpvor
   ! create output fileset
 
   ipk(:)= npk                   ! Those three variables are  3D
-  stypvar%cunits            = 'kg.m-4.s-1'
+  stypvar%cunits            = '1.e-7 kg.m-4.s-1'
   stypvar%rmissing_value    = 0.
-  stypvar%valid_min         = -1000.
-  stypvar%valid_max         = 1000.
+  stypvar%valid_min         = -10000.
+  stypvar%valid_max         = 10000.
   stypvar%conline_operation = 'N/A'
   stypvar%caxis             = 'TZYX'
 
+  DO ji = 1, nvar
+   stypvar(ji)%ichunk = (/npiglo,MAX(1,npjglo/30), 1, 1 /)
+  ENDDO
+
   IF (lertel ) THEN
      ! define variable name and attribute
      stypvar(1)%cname = 'vorelvor' ; stypvar(1)%clong_name = 'Relative_component_of_Ertel_PV'
diff --git a/cdfrhoproj.f90 b/src/cdfrhoproj.f90
similarity index 70%
rename from cdfrhoproj.f90
rename to src/cdfrhoproj.f90
index a97b456..9bdbe52 100644
--- a/cdfrhoproj.f90
+++ b/src/cdfrhoproj.f90
@@ -28,7 +28,7 @@ PROGRAM cdfrhoproj
 
   INTEGER(KIND=4)                               :: ji,jj,jk,jsig,jfich, jvar
   INTEGER(KIND=4)                               :: npiglo, npjglo
-  INTEGER(KIND=4)                               :: npk, npsig, npt
+  INTEGER(KIND=4)                               :: npk, npsig=1, npt
   INTEGER(KIND=4)                               :: nvars, nvout=2
   INTEGER(KIND=4)                               :: narg, iargc
   INTEGER(KIND=4)                               :: ijarg, ireq
@@ -37,7 +37,8 @@ PROGRAM cdfrhoproj
   INTEGER(KIND=4)                               :: nfilin
   INTEGER(KIND=4)                               :: numlev=10
   INTEGER(KIND=4)                               :: ncout, ierr
-  INTEGER(KIND=4), DIMENSION(2)                 :: ipk, id_varout ! for output variables
+  INTEGER(KIND=4)                               :: nbins
+  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: ipk, id_varout ! for output variables
   !
   REAL(KIND=4), DIMENSION(:,:,:),   ALLOCATABLE :: zsig, alpha
   REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: v2dint, zint, v2d
@@ -46,6 +47,7 @@ PROGRAM cdfrhoproj
   REAL(KIND=4)                                  :: zalpha
   REAL(KIND=4)                                  :: zspvalo=999999.
   REAL(KIND=4)                                  :: zspvali=0.
+  REAL(KIND=4)                                  :: sigmin, sigstp
 
   CHARACTER(LEN=256)                            :: cf_rholev='rho_lev'
   CHARACTER(LEN=256)                            :: cf_dta
@@ -57,28 +59,33 @@ PROGRAM cdfrhoproj
   CHARACTER(LEN=256)                            :: cldum
   CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_names     ! temporary arry for variable name in file
  
-  TYPE(variable), DIMENSION(2)                  :: stypvar      ! structure for attributes
-  TYPE(variable), DIMENSION(:),     ALLOCATABLE :: stypzvar      ! structure for attributes
+  TYPE(variable), DIMENSION(:),     ALLOCATABLE :: stypvar      ! structure for attributes
+  TYPE(variable), DIMENSION(:),     ALLOCATABLE :: stypzvar     ! structure for attributes
   !
   LOGICAL                                       :: lsingle =.FALSE.
   LOGICAL                                       :: lchk    =.FALSE.
   LOGICAL                                       :: lisodep =.FALSE.
+  LOGICAL                                       :: liso    =.TRUE.
+  LOGICAL                                       :: ldebug  =.FALSE.
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
   cv_sig = cn_vosigma0
 
   narg=iargc()
   IF ( narg < 3 ) THEN
-     PRINT *,' usage : cdfrhoproj IN-var RHO-file List_of_IN-files [VAR-type] ... '
-     PRINT *,'                ... [-s0 sig0 ] [-sig sigma_name] [-isodep ]'
+     PRINT *,' usage : cdfrhoproj IN-var RHO-file List_of_IN-files [VAR-type] [-debug ]... '
+     PRINT *,'       ... [-isodep] [-s0 sig0 | -s0 sigmin,sigstp,nbins ] [-sig sigma_name]..'
+     PRINT *,'       ... [-noiso]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
-     PRINT *,'       Project IN-var on isopycnal surfaces defined either by sig0 given' 
-     PRINT *,'       as argument or on all sigma surfaces defined in ',TRIM(cf_rholev),' ascii file.'
+     PRINT *,'       Project IN-var on isopycnal surfaces. The isosurfaces can be defined in'
+     PRINT *,'       many ways : (1) In a pre-defined ASCII file named ',TRIM(cf_rholev),'see format'
+     PRINT *,'       below.  (2) using -s0 option.'
      PRINT *,'       IN-var will be interpolated on the T point of the C-grid, previous'
      PRINT *,'       to projection on isopycnal.'
-     PRINT *,'       This cdftool is one of the few using 3D arrays. Further development is '
-     PRINT *,'       required to work with vertical slabs instead.'
+     PRINT *,'       '
+     PRINT *,'       WARNING: This cdftool is one of the few using 3D arrays. Further '
+     PRINT *,'       development is required to work with vertical slabs instead.'
      PRINT *,'      '
      PRINT *,'     ARGUMENTS :'
      PRINT *,'       IN-var   : name of the input variable to be projected' 
@@ -88,15 +95,22 @@ PROGRAM cdfrhoproj
      PRINT *,'       List_of_IN-file  : netcdf files with IN-var '
      PRINT *,'      '
      PRINT *,'     OPTIONS :'
-     PRINT *,'       [-s0 sigma ] : define a single sigma surface on the command line' 
-     PRINT *,'                    instead of reading rho_lev ascii file.'
-     PRINT *,'       [VAR-type] : position of IN-var on the C-grid ( either T U V F W )'
-     PRINT *,'                    default is ''T''.'
+     PRINT *,'       [-s0 sigma  | -s0 sigmin,sigstp,nbins ]  : In the first form define a '
+     PRINT *,'                    single sigma surface on the command line, while in the 2nd'
+     PRINT *,'                    form, it uses the same numbers than cdfmocsig to define'
+     PRINT *,'                    equally spaced (sigstp) density surfaces, starting from '
+     PRINT *,'                    sigmin and up to sigmin + (nbins)*sigstp'
+     PRINT *,'                    This option prevails the use of ',TRIM(cf_rholev),' file.'
+     PRINT *,'       [VAR-type] : position of IN-var on the C-grid ( either T U V F W S )'
+     PRINT *,'                    default is ''T''. '
+     PRINT *,'                    S is used in case of section files (cdf_xtract_brokenline).'
      PRINT *,'       [-sig sigma_name] : name of the density variable in RHO_file.'
      PRINT *,'                    default is ', TRIM(cv_sig)
      PRINT *,'       [-isodep ] : only compute the isopycnal depth. then stop. In this case'
      PRINT *,'                    you must still specify a IN-var variable (in fact a dummy'
      PRINT *,'                     name).'
+     PRINT *,'       [-noiso]   : do not save isopycnal depth (suitable for big files).'
+     PRINT *,'       [-debug]   : produce extra prints. Must be use before other options ..'
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'       no metrics, information is taken from depth variable in input files.'
@@ -115,7 +129,7 @@ PROGRAM cdfrhoproj
      PRINT *,'         variables : ',TRIM(cn_vodepiso),' (m) '
      PRINT *,'      '
      PRINT *,'     SEE ALSO :'
-     PRINT *,'       replace cdfisopycdep when using -isodep option.'
+     PRINT *,'       replace cdfisopycdep when using -isodep option,  cdfmocsig'
      PRINT *,'       '
      STOP
   ENDIF
@@ -126,13 +140,16 @@ PROGRAM cdfrhoproj
     CALL getarg( ijarg, cldum) ; ijarg=ijarg+1
     SELECT CASE ( cldum )
     CASE ('-s0') 
-       npsig = 1 ; lsingle=.TRUE. ; ALLOCATE (zi(npsig) )
-       CALL getarg( ijarg, cldum) ; ijarg=ijarg+1 ; READ(cldum,*) zi(1)
+       CALL getarg( ijarg, cldum) ; ijarg=ijarg+1 
+       CALL ParseS0Opt(cldum) 
+       lsingle=.TRUE.
     CASE ( 'T','t','U','u','V','v','W','w','F','f' )
        ctype=cldum
     CASE ('-sig') 
        CALL getarg( ijarg, cv_sig) ; ijarg=ijarg+1 
     CASE ('-isodep')  ; lisodep = .TRUE. ; nvout=1 ; cf_out='isopycdep.nc'
+    CASE ('-noiso' )  ; liso    = .FALSE.; nvout=1
+    CASE ('-debug' )  ; ldebug  = .TRUE.
     CASE DEFAULT 
        ireq=ireq+1
        SELECT CASE (ireq )
@@ -153,10 +170,12 @@ PROGRAM cdfrhoproj
   IF ( .NOT.  lsingle ) THEN
      OPEN(numlev,FILE=cf_rholev)
      READ(numlev,*) npsig
+     IF (ldebug) PRINT *, TRIM(cf_rholev),' contains :'
+     IF (ldebug) PRINT *, npsig
      ALLOCATE ( zi(npsig) )
      DO jsig=1,npsig
         READ(numlev,*) zi(jsig)
-        PRINT *,zi(jsig)
+        IF (ldebug) PRINT *,zi(jsig)
      END DO
      CLOSE(numlev)
   ENDIF
@@ -170,6 +189,7 @@ PROGRAM cdfrhoproj
   CALL getarg(istartarg, cf_dta)
   nvars=getnvar(cf_dta)
   ALLOCATE(cv_names(nvars), stypzvar(nvars))
+  ALLOCATE(ipk(nvout), id_varout(nvout), stypvar(nvout) )
 
   cv_names(:)=getvarname(cf_dta, nvars, stypzvar)
 
@@ -186,6 +206,7 @@ PROGRAM cdfrhoproj
 
   !! ** Compute interpolation coefficients as well as the level used
   !!    to interpolate between
+  !$OMP PARALLEL DO SCHEDULE(RUNTIME)
   DO ji=1,npiglo
      DO jj = 1, npjglo
         ijk = 1
@@ -212,6 +233,7 @@ PROGRAM cdfrhoproj
         END DO
      END DO
   END DO
+  !$OMP END PARALLEL DO
 
   IF ( lisodep ) THEN
      ipk(1)                       = npsig
@@ -230,6 +252,7 @@ PROGRAM cdfrhoproj
      ierr  = putheadervar(ncout , cf_rhofil, npiglo, npjglo, npsig, pdep=zi )
 
      DO jsig=1,npsig
+        !$OMP PARALLEL DO SCHEDULE(RUNTIME)
         DO ji=1,npiglo
            DO jj=1,npjglo
              ! ik0 is retrieved from alpha, taking the integer part.
@@ -250,8 +273,10 @@ PROGRAM cdfrhoproj
              ENDIF
            END DO
         END DO
+        !$OMP END PARALLEL DO
         ierr = putvar(ncout, id_varout(1), zint , jsig, npiglo, npjglo)
      END DO
+     ierr = putvar1d(ncout, tim, 1, 'T')
      ierr = closeout(ncout    )
      STOP ' -isodep option in use: only compute depth of isopycnal surfaces.'
   ENDIF
@@ -274,7 +299,7 @@ PROGRAM cdfrhoproj
      DO jk=1,npk
         v2d(:,:) = getvar(cf_dta,cv_in,jk,npiglo,npjglo)
         SELECT CASE ( ctype )
-        CASE ('T', 't' )
+        CASE ('T', 't', 'S', 's' )
            zsig(:,:,jk) = v2d(:,:)
         CASE ('U','u' )
            DO ji=2,npiglo
@@ -308,31 +333,38 @@ PROGRAM cdfrhoproj
      ipk(:)=npsig
      DO jvar=1,nvars
        IF ( cv_in == stypzvar(jvar)%cname ) THEN 
-          stypvar(2)=stypzvar(jvar)
+          stypvar(1)=stypzvar(jvar)
           EXIT
        ENDIF
      END DO
-     stypvar(2)%clong_name        = TRIM(stypvar(2)%clong_name)//' on iso sigma'
-     stypvar(2)%rmissing_value    = zspvalo
-     stypvar(2)%caxis             = 'TRYX'
-
-     stypvar(1)%cname             = cn_vodepiso
-     stypvar(1)%cunits            = 'm'
-     stypvar(1)%rmissing_value    = 999999.
-     stypvar(1)%valid_min         = 0.
-     stypvar(1)%valid_max         = 7000.
-     stypvar(1)%clong_name        = 'Depth_of_Isopycnals'
-     stypvar(1)%cshort_name       = cn_vodepiso
-     stypvar(1)%conline_operation = 'N/A'
+     stypvar(1)%clong_name        = TRIM(stypvar(2)%clong_name)//' on iso sigma'
+     stypvar(1)%rmissing_value    = zspvalo
      stypvar(1)%caxis             = 'TRYX'
 
+     IF ( liso ) THEN
+       stypvar(2)%cname             = cn_vodepiso
+       stypvar(2)%cunits            = 'm'
+       stypvar(2)%rmissing_value    = 999999.
+       stypvar(2)%valid_min         = 0.
+       stypvar(2)%valid_max         = 7000.
+       stypvar(2)%clong_name        = 'Depth_of_Isopycnals'
+       stypvar(2)%cshort_name       = cn_vodepiso
+       stypvar(2)%conline_operation = 'N/A'
+       stypvar(2)%caxis             = 'TRYX'
+     ENDIF
+
      cf_out=TRIM(cf_dta)//'.interp'
+     PRINT *, npsig, zi, TRIM(cf_out)
  
      ncout = create      (cf_out, cf_rhofil, npiglo, npjglo, npsig          )
+     print *, ncout
      ierr  = createvar   (ncout,  stypvar,   nvout,  ipk,    id_varout      )
+     print *, ierr
      ierr  = putheadervar(ncout , cf_rhofil, npiglo, npjglo, npsig, pdep=zi )
+     print *, ierr
  
      DO jsig=1,npsig
+        !$OMP PARALLEL DO SCHEDULE(RUNTIME)
         DO ji=1,npiglo
            DO jj=1,npjglo
              ! ik0 is retrieved from alpha, taking the integer part.
@@ -345,23 +377,85 @@ PROGRAM cdfrhoproj
                 IF (P1 /= zspvali .AND. P2 /= zspvali) THEN
                    v2dint(ji,jj) = zalpha *P2  &
                      &         +(1-zalpha)*P1
-                    zint (ji,jj) = zalpha *h1d(ik0+1) &
+                    IF( liso) zint (ji,jj) = zalpha *h1d(ik0+1) &
                      &         +(1-zalpha)*h1d(ik0  )
                 ELSE 
                    v2dint(ji,jj)=zspvalo
-                   zint  (ji,jj)=zspvalo
+                   IF( liso )zint  (ji,jj)=zspvalo
                ENDIF
              ELSE 
                v2dint(ji,jj)=zspvalo
-               zint  (ji,jj)=zspvalo
+               IF ( liso ) zint  (ji,jj)=zspvalo
              ENDIF
            END DO
         END DO
-        ierr = putvar(ncout, id_varout(1), zint  , jsig, npiglo, npjglo)
-        ierr = putvar(ncout, id_varout(2), v2dint, jsig, npiglo, npjglo)
+        !$OMP END PARALLEL DO
+                  ierr = putvar(ncout, id_varout(1), v2dint, jsig, npiglo, npjglo)
+        IF (liso) ierr = putvar(ncout, id_varout(2), zint  , jsig, npiglo, npjglo)
      END DO
      ierr = putvar1d(ncout, tim, 1, 'T')
      ierr = closeout(ncout             )
   END DO  ! loop on scalar files
         PRINT *,'Projection on isopycns completed successfully'
+
+  CONTAINS
+
+  SUBROUTINE ParseS0Opt(cdum )
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE ParseS0Opt  ***
+    !!
+    !! ** Purpose :  Parse -s0 option if used to set up the equally spaced
+    !!               isopycnal surfaces to use for projection 
+    !!
+    !! ** Method  :  Assume cdum is a comma separated list, use global module
+    !!               variables.
+    !!----------------------------------------------------------------------
+      CHARACTER(LEN=*), INTENT(in) :: cdum
+
+      CHARACTER(LEN=80), DIMENSION(100) :: cl_dum  ! 100 is arbitrary
+      INTEGER  :: ji
+      INTEGER  :: inchar,  i1=1
+      !!----------------------------------------------------------------------
+      inchar= LEN(TRIM(cdum))
+      ! scan the input string and look for ',' as separator
+      DO ji=1,inchar
+         IF ( cdum(ji:ji) == ',' ) THEN
+            cl_dum(npsig) = cdum(i1:ji-1)
+            i1=ji+1
+            npsig=npsig+1
+         ENDIF
+      ENDDO
+      ! last name of the list does not have a ','
+      cl_dum(npsig) = cdum(i1:inchar)
+
+      IF ( npsig == 3 ) THEN  ! sigmin,sigstp,nbins
+         READ(cl_dum(1),*) sigmin
+         READ(cl_dum(2),*) sigstp
+         READ(cl_dum(3),*) nbins
+         npsig = nbins + 1
+      ELSE IF (npsig == 1 ) THEN ! single value
+         READ(cl_dum(1),*) sigmin
+         nbins  = 0
+         sigstp = 0.
+      ELSE
+         PRINT *,' Error in -s0 option : either -s0 val  or -s0 sigmin,sigstp,nbins'
+         STOP
+      ENDIF
+
+      ALLOCATE ( zi(npsig) )
+      zi(1) = sigmin
+      DO ji=2, nbins+1
+         zi(ji) = zi(ji-1) + sigstp
+      ENDDO
+      IF ( ldebug ) THEN
+        PRINT *, TRIM(cf_rholev),' like output '
+        PRINT *, '---------------------'
+        PRINT *, npsig
+        DO ji = 1, npsig
+          PRINT *, zi(ji)
+        END DO
+      ENDIF
+
+   END SUBROUTINE ParseS0Opt
+
 END  PROGRAM cdfrhoproj
diff --git a/cdfrichardson.f90 b/src/cdfrichardson.f90
similarity index 100%
rename from cdfrichardson.f90
rename to src/cdfrichardson.f90
diff --git a/cdfrmsssh.f90 b/src/cdfrmsssh.f90
similarity index 87%
rename from cdfrmsssh.f90
rename to src/cdfrmsssh.f90
index ea589b1..1284637 100644
--- a/cdfrmsssh.f90
+++ b/src/cdfrmsssh.f90
@@ -21,7 +21,7 @@ PROGRAM cdfrmsssh
 
   INTEGER(KIND=4)                            :: jk, jt            ! dummy loop index
   INTEGER(KIND=4)                            :: narg, iargc       ! command line
-  INTEGER(KIND=4)                            :: ijarg, ireq       ! command line
+  INTEGER(KIND=4)                            :: ijarg, ixtra      ! command line
   INTEGER(KIND=4)                            :: npiglo, npjglo    ! size of the domain
   INTEGER(KIND=4)                            :: npk, npt          ! size of the domain
   INTEGER(KIND=4)                            :: ncout             ! ncid of output variable
@@ -42,6 +42,7 @@ PROGRAM cdfrmsssh
   TYPE(variable), DIMENSION(1)               :: stypvaro          ! output data structure
 
   LOGICAL                                    :: lchk = .FALSE.    ! flag for missing files
+  LOGICAL                                    :: lnc4 = .FALSE.    ! flag for missing files
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
@@ -49,7 +50,7 @@ PROGRAM cdfrmsssh
 
   narg= iargc()
   IF ( narg < 2 ) THEN
-     PRINT *,' usage : cdfrmsssh T-file T2-file '
+     PRINT *,' usage : cdfrmsssh T-file T2-file [-nc4] [-o outputfile]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
      PRINT *,'       Compute the standard deviation of the SSH from its'
@@ -65,6 +66,11 @@ PROGRAM cdfrmsssh
      PRINT *,'       T-file  : netcdf file with mean values for SSH' 
      PRINT *,'       T2-file : netcdf file with mean squared values for SSH' 
      PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'       [-nc4] : use netcdf4 with chunking and deflation '
+     PRINT *,'       [-o output file ] : specify the name of the output file instead'
+     PRINT *,'                          of default name ', TRIM(cf_out)
+     PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'       none' 
      PRINT *,'      '
@@ -77,13 +83,15 @@ PROGRAM cdfrmsssh
      STOP
   ENDIF
 
-  ijarg = 1  ; ireq = 0
+  ijarg = 1  ; ixtra = 0
   DO WHILE ( ijarg <= narg) 
      CALL getarg(ijarg, cldum ) ; ijarg=ijarg+1
      SELECT CASE ( cldum )
+     CASE ( '-nc4' ) ; lnc4 = .TRUE.
+     CASE ( '-o'   ) ; CALL getarg(ijarg, cf_out ) ; ijarg=ijarg+1
      CASE DEFAULT
-        ireq = ireq + 1
-        SELECT CASE ( ireq ) 
+        ixtra = ixtra + 1
+        SELECT CASE ( ixtra ) 
         CASE ( 1 ) ; cf_in  = cldum
         CASE ( 2 ) ; cf_in2 = cldum
         CASE DEFAULT
@@ -103,6 +111,7 @@ PROGRAM cdfrmsssh
   npt    = getdim (cf_in, cn_t)
 
   ipko(1) = 1
+  stypvaro(1)%ichunk            = (/npiglo, MAX(1,npjglo/30), 1, 1 /)
   stypvaro(1)%cname             = TRIM(cv_in)//'_rms'
   stypvaro(1)%cunits            = 'm'
   stypvaro(1)%rmissing_value    = 0.
@@ -121,9 +130,9 @@ PROGRAM cdfrmsssh
   ALLOCATE( zvbar(npiglo,npjglo), zvba2(npiglo,npjglo) )
   ALLOCATE( dsdev(npiglo,npjglo), tim(npt)             )
 
-  ncout = create      (cf_out, cf_in,    npiglo, npjglo, npk       )
-  ierr  = createvar   (ncout,  stypvaro, 1,      ipko,   id_varout )
-  ierr  = putheadervar(ncout,  cf_in,    npiglo, npjglo, npk       )
+  ncout = create      (cf_out, cf_in,    npiglo, npjglo, npk       , ld_nc4=lnc4 )
+  ierr  = createvar   (ncout,  stypvaro, 1,      ipko,   id_varout , ld_nc4=lnc4 )
+  ierr  = putheadervar(ncout,  cf_in,    npiglo, npjglo, npk                     )
 
   cv_in2 = TRIM(cv_in)//'_sqd'
   DO jt = 1, npt
diff --git a/cdfscale.f90 b/src/cdfscale.f90
similarity index 100%
rename from cdfscale.f90
rename to src/cdfscale.f90
diff --git a/cdfsections.f90 b/src/cdfsections.f90
similarity index 99%
rename from cdfsections.f90
rename to src/cdfsections.f90
index a87b1aa..ea5a16c 100644
--- a/cdfsections.f90
+++ b/src/cdfsections.f90
@@ -5,7 +5,7 @@ program cdfsections
 !
 ! ** Purpose : extract oceanic fields along a track made of several sections.
 !
-! ** Method : computes N sections by taking the nearest point north of 60�N 
+! ** Method : computes N sections by taking the nearest point north of 60N 
 !             and near undefined values (bottom or coasts), and interpolates 
 !             between the four nearest points elsewhere.
 !             
@@ -19,7 +19,7 @@ program cdfsections
 ! WARNING : 
 !  - require large memory : reduce domain size with ncks if insufficient memory error.
 !  - does not work if the section crosses the Greenwich line (easy to modify if needed).
-!  - not yet tested north of 60�N (but should work) ...
+!  - not yet tested north of 60N (but should work) ...
 !
 ! history :
 ! N. JOURDAIN (LEGI-MEOM), April 2009
@@ -112,7 +112,7 @@ REAL*8,ALLOCATABLE,DIMENSION(:) :: d, X1
      PRINT *,' It is recommended to put a lot of points on each section if the aim'
      PRINT *,' is to compute X-integrations along the section (10 x the model resolution).'
      PRINT *,'NB : sections cannot cross the Greenwich line !!'
-     PRINT *,'NB : Not yet tested north of 60�N.'
+     PRINT *,'NB : Not yet tested north of 60N.'
      PRINT *,'NB : require a large amount of memory !' 
      PRINT *,'     -> reduce domain size with  ncks -d  if insufficient memory error.'
      PRINT *,' '
diff --git a/cdfsig0.f90 b/src/cdfsig0.f90
similarity index 64%
copy from cdfsig0.f90
copy to src/cdfsig0.f90
index 2b67c38..5647813 100644
--- a/cdfsig0.f90
+++ b/src/cdfsig0.f90
@@ -23,9 +23,9 @@ PROGRAM cdfsig0
 
   INTEGER(KIND=4)                           :: jk, jt             ! dummy loop index
   INTEGER(KIND=4)                           :: ierr               ! error status
-  INTEGER(KIND=4)                           :: narg, iargc        ! browse command line
+  INTEGER(KIND=4)                           :: narg, ijarg,iargc        ! browse command line
   INTEGER(KIND=4)                           :: npiglo, npjglo     ! size of the domain
-  INTEGER(KIND=4)                           :: npk, npt           ! size of the domain
+  INTEGER(KIND=4)                           :: npk, npkk, npt     ! size of the domain
   INTEGER(KIND=4)                           :: ncout              ! ncid of output file
   INTEGER(KIND=4), DIMENSION(1)             :: ipk, id_varout     ! level and  varid's
 
@@ -37,20 +37,32 @@ PROGRAM cdfsig0
 
   CHARACTER(LEN=256)                        :: cf_tfil            ! input filename
   CHARACTER(LEN=256)                        :: cf_out='sig0.nc'   ! output file name
+  CHARACTER(LEN=256)                        :: cldum              ! dummy characte variable variable
+  CHARACTER(LEN=256)                        :: cv_sal             ! salinity name in netcdf
+  CHARACTER(LEN=256)                        :: cv_tem             ! temperature name in netcdf
 
   TYPE (variable), DIMENSION(1)             :: stypvar            ! structure for attributes
+  LOGICAL                                   :: lnc4 = .FALSE.     ! flag for missing files
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
   narg = iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfsig0 T-file'
+     PRINT *,' usage : cdfsig0 -t T-file [-sal SAL-name] [-tem TEM-name] [-nc4] [-o OUT-file]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
      PRINT *,'       Compute potential density (sigma-0) refered to the surface.' 
      PRINT *,'      '
      PRINT *,'     ARGUMENTS :'
-     PRINT *,'       T-file  : netcdf file with temperature and salinity.' 
+     PRINT *,'       -t T-file  : netcdf file with temperature and salinity.' 
+     PRINT *,'         (for backward compatibility, -t can be ommited when T-file is the only'
+     PRINT *,'         argument.)'
+     PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'       [-sal SAL-name]  : name of salinity variable'
+     PRINT *,'       [-tem TEM-name]  : name of temperature variable'
+     PRINT *,'       [-nc4]  : enable chunking and compression'
+     PRINT *,'       [-o OUT-file]    : specify output filename instead of ',TRIM(cf_out)
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'        none'
@@ -64,7 +76,27 @@ PROGRAM cdfsig0
      STOP
   ENDIF
 
-  CALL getarg (1, cf_tfil)
+  ijarg=1
+  cv_sal=cn_vosaline
+  cv_tem=cn_votemper
+  DO WHILE ( ijarg <= narg )
+     CALL getarg(ijarg, cldum ) ; ijarg=ijarg+1
+     SELECT CASE ( cldum )
+     CASE ( '-t'   ) ; CALL getarg(ijarg, cf_tfil) ; ijarg=ijarg+1
+     CASE ( '-o'   ) ; CALL getarg(ijarg, cf_out ) ; ijarg=ijarg+1
+     CASE ( '-sal' ) ; CALL getarg(ijarg, cv_sal ) ; ijarg=ijarg+1
+     CASE ( '-tem' ) ; CALL getarg(ijarg, cv_tem ) ; ijarg=ijarg+1
+     CASE ( '-nc4' ) ; lnc4 = .TRUE.
+     CASE DEFAULT
+      IF ( narg == 1 ) THEN
+         cf_tfil = cldum
+      ELSE
+         PRINT *,' option ',TRIM(cldum),' not understood'
+         STOP
+      ENDIF
+     END SELECT
+  ENDDO
+ 
   IF (chkfile(cf_tfil) ) STOP ! missing file
 
   npiglo = getdim (cf_tfil, cn_x)
@@ -72,7 +104,10 @@ PROGRAM cdfsig0
   npk    = getdim (cf_tfil, cn_z)
   npt    = getdim (cf_tfil, cn_t)
 
-  ipk(:)                       = npk  ! all variables (input and output are 3D)
+  npkk=npk
+  IF ( npk == 0 ) npkk=1
+
+  ipk(:)                       = npkk  ! all variables (input and output are 3D)
   stypvar(1)%cname             = cn_vosigma0
   stypvar(1)%cunits            = 'kg/m3'
   stypvar(1)%rmissing_value    = 0.
@@ -82,6 +117,8 @@ PROGRAM cdfsig0
   stypvar(1)%cshort_name       = cn_vosigma0
   stypvar(1)%conline_operation = 'N/A'
   stypvar(1)%caxis             = 'TZYX'
+  stypvar(1)%ichunk            = (/npiglo, MAX(1,npjglo/30), 1, 1 /)
+
 
   PRINT *, 'npiglo = ', npiglo
   PRINT *, 'npjglo = ', npjglo
@@ -93,8 +130,8 @@ PROGRAM cdfsig0
   ALLOCATE (tim(npt) )
 
   ! create output fileset
-  ncout = create      (cf_out, cf_tfil, npiglo, npjglo, npk       )
-  ierr  = createvar   (ncout,  stypvar, 1,      ipk,    id_varout )
+  ncout = create      (cf_out, cf_tfil, npiglo, npjglo, npk,       ld_nc4=lnc4  )
+  ierr  = createvar   (ncout,  stypvar, 1,      ipk,    id_varout, ld_nc4=lnc4  )
   ierr  = putheadervar(ncout,  cf_tfil, npiglo, npjglo, npk       )
 
   tim=getvar1d(cf_tfil, cn_vtimec, npt     )
@@ -102,14 +139,14 @@ PROGRAM cdfsig0
 
   DO jt=1,npt
      PRINT *,' TIME = ', jt, tim(jt)/86400.,' days'
-     DO jk = 1, npk
+     DO jk = 1, npkk
         zmask(:,:)=1.
 
-        ztemp(:,:)= getvar(cf_tfil, cn_votemper, jk, npiglo, npjglo, ktime=jt)
-        zsal(:,:) = getvar(cf_tfil, cn_vosaline, jk, npiglo, npjglo, ktime=jt)
+        ztemp(:,:)= getvar(cf_tfil, cv_tem, jk, npiglo, npjglo, ktime=jt)
+        zsal(:,:) = getvar(cf_tfil, cv_sal, jk, npiglo, npjglo, ktime=jt)
 
         ! assuming spval is 0
-        WHERE( zsal == 0 ) zmask = 0
+        WHERE( zsal <= 0 ) zmask = 0
 
         zsig0(:,:) = sigma0 (ztemp, zsal, npiglo, npjglo )* zmask(:,:)
 
diff --git a/cdfsigi.f90 b/src/cdfsigi.f90
similarity index 100%
rename from cdfsigi.f90
rename to src/cdfsigi.f90
diff --git a/cdfsiginsitu.f90 b/src/cdfsiginsitu.f90
similarity index 60%
rename from cdfsiginsitu.f90
rename to src/cdfsiginsitu.f90
index 198e9da..ed0504a 100644
--- a/cdfsiginsitu.f90
+++ b/src/cdfsiginsitu.f90
@@ -23,13 +23,14 @@ PROGRAM cdfsiginsitu
   IMPLICIT NONE
   INTEGER(KIND=4)                           :: jk, jt             ! dummy loop index
   INTEGER(KIND=4)                           :: ierr               ! error status
-  INTEGER(KIND=4)                           :: narg, iargc        ! browse command line
+  INTEGER(KIND=4)                           :: narg, iargc, ijarg ! browse command line
   INTEGER(KIND=4)                           :: npiglo, npjglo     ! size of the domain
-  INTEGER(KIND=4)                           :: npk, npt           ! size of the domain
+  INTEGER(KIND=4)                           :: npk, npkk, npt     ! size of the domain
   INTEGER(KIND=4)                           :: ncout              ! ncid of output file
   INTEGER(KIND=4), DIMENSION(1)             :: ipk, id_varout     ! level and  varid's
 
   REAL(KIND=4)                              :: zspval             ! missing value
+  REAL(KIND=4)                              :: dep=0.0            ! depth to be used
   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: ztemp              ! temperature
   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zsal               ! salinity
   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zsigi              ! sigma-insitu
@@ -39,27 +40,42 @@ PROGRAM cdfsiginsitu
 
   CHARACTER(LEN=256)                        :: cf_tfil             ! input filename
   CHARACTER(LEN=256)                        :: cf_out='siginsitu.nc' ! output file name
+  CHARACTER(LEN=256)                        :: cldum              ! dummy characte variable variable
+  CHARACTER(LEN=256)                        :: cv_sal             ! salinity name in netcdf
+  CHARACTER(LEN=256)                        :: cv_tem             ! temperature name in netcdf
 
   TYPE (variable), DIMENSION(1)             :: stypvar            ! structure for attributes
+  LOGICAL                                   :: lnc4 = .FALSE.     ! flag for missing files
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
   narg = iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfsiginsitu T-file'
+     PRINT *,' usage : cdfsiginsitu -t T-file [-sal SAL-name] [-tem TEM-name ] ...'
+     PRINT *,'                [-dep depth] [-o OUT-file ] [-nc4 ] '
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
      PRINT *,'       Compute in situ density from temperature and salinity.' 
      PRINT *,'       Depths are taken from input file.'
      PRINT *,'      '
      PRINT *,'     ARGUMENTS :'
-     PRINT *,'       T-file : netcdf file with temperature and salinity.' 
+     PRINT *,'       -t T-file : netcdf file with temperature and salinity.' 
+     PRINT *,'         (for backward compatibility, -t can be ommited when T-file is the only'
+     PRINT *,'         argument.)'
+     PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'       [-sal SAL-name] : name of salinity variable'
+     PRINT *,'       [-tem TEM-name] : name of temperature variable'
+     PRINT *,'       [-dep depth ]   : depth to be used in case of 2D input file (only)'
+     PRINT *,'       [-nc4]          : enable chunking and compression'
+     PRINT *,'       [-o OUT-file]   : specify output filename instead of ',TRIM(cf_out)
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'        none'
      PRINT *,'      '
      PRINT *,'     OUTPUT : '
-     PRINT *,'       netcdf file : ', TRIM(cf_out) 
+     PRINT *,'       netcdf file : ', TRIM(cf_out) ,'or the file name specified '
+     PRINT *,'                   with -o option'
      PRINT *,'         variables : vosigmainsitu (kg/m3 -1000 )'
      PRINT *,'      '
      PRINT *,'     SEE ALSO :'
@@ -68,7 +84,27 @@ PROGRAM cdfsiginsitu
      STOP
   ENDIF
 
-  CALL getarg (1, cf_tfil)
+  ijarg=1
+  cv_sal=cn_vosaline
+  cv_tem=cn_votemper
+  DO WHILE ( ijarg <= narg )
+     CALL getarg(ijarg, cldum ) ; ijarg=ijarg+1
+     SELECT CASE ( cldum )
+     CASE ( '-t'   ) ; CALL getarg(ijarg, cf_tfil) ; ijarg=ijarg+1
+     CASE ( '-o'   ) ; CALL getarg(ijarg, cf_out ) ; ijarg=ijarg+1
+     CASE ( '-sal' ) ; CALL getarg(ijarg, cv_sal ) ; ijarg=ijarg+1
+     CASE ( '-tem' ) ; CALL getarg(ijarg, cv_tem ) ; ijarg=ijarg+1
+     CASE ( '-dep' ) ; CALL getarg(ijarg, cldum  ) ; ijarg=ijarg+1 ; READ(cldum,*) dep 
+     CASE ( '-nc4' ) ; lnc4 = .TRUE.
+     CASE DEFAULT
+      IF ( narg == 1 ) THEN
+         cf_tfil = cldum
+      ELSE
+         PRINT *,' option ',TRIM(cldum),' not understood'
+         STOP
+      ENDIF
+     END SELECT
+  ENDDO
 
   IF ( chkfile(cf_tfil) ) STOP ! missing file
 
@@ -76,8 +112,14 @@ PROGRAM cdfsiginsitu
   npjglo = getdim (cf_tfil,cn_y)
   npk    = getdim (cf_tfil,cn_z)
   npt    = getdim (cf_tfil,cn_t)
+  
 
-  ipk(:)= npk  ! all variables (input and output are 3D)
+  IF ( npk == 0 ) THEN
+   npkk = 1
+  ELSE
+   npkk = npk  ! all variables (input and output are 3D)
+  ENDIF
+  ipk(:) = npkk
   stypvar(1)%cname             = 'vosigmainsitu'
   stypvar(1)%cunits            = 'kg/m3'
   stypvar(1)%rmissing_value    = 0.
@@ -87,6 +129,7 @@ PROGRAM cdfsiginsitu
   stypvar(1)%cshort_name       = 'vosigmainsitu'
   stypvar(1)%conline_operation = 'N/A'
   stypvar(1)%caxis             = 'TZYX'
+  stypvar(1)%ichunk            = (/npiglo, MAX(1,npjglo/30), 1, 1 /)
 
   PRINT *, 'npiglo = ', npiglo
   PRINT *, 'npjglo = ', npjglo
@@ -95,26 +138,30 @@ PROGRAM cdfsiginsitu
 
   ALLOCATE (ztemp(npiglo,npjglo), zsal (npiglo,npjglo) )
   ALLOCATE (zsigi(npiglo,npjglo), zmask(npiglo,npjglo) )
-  ALLOCATE (gdept(npk), tim(npt)                       )
+  ALLOCATE (gdept(npkk), tim(npt)                       )
 
   ! create output fileset
-  ncout = create      (cf_out, cf_tfil,  npiglo, npjglo, npk       )
-  ierr  = createvar   (ncout,  stypvar,  1,      ipk,    id_varout )
+  ncout = create      (cf_out, cf_tfil,  npiglo, npjglo, npk,       ld_nc4=lnc4 )
+  ierr  = createvar   (ncout,  stypvar,  1,      ipk,    id_varout, ld_nc4=lnc4 )
   ierr  = putheadervar(ncout,  cf_tfil,  npiglo, npjglo, npk       )
 
-  zspval = getatt(cf_tfil, cn_vosaline, 'missing_value')
+  zspval = getatt(cf_tfil, cv_sal, 'missing_value')
 
-  gdept = getvar1d(cf_tfil, cn_vdeptht, npk    )
+  IF ( npk == 0 ) THEN
+    gdept(:)= dep
+  ELSE
+    gdept = getvar1d(cf_tfil, cn_vdeptht, npk    )
+  ENDIF
   tim   = getvar1d(cf_tfil, cn_vtimec, npt     )
   ierr  = putvar1d(ncout,  tim,        npt, 'T')
 
   DO jt = 1, npt
      PRINT *,'time: ',jt
-     DO jk = 1, npk
+     DO jk = 1, npkk
         zmask(:,:) = 1.
 
-        ztemp(:,:) = getvar(cf_tfil, cn_votemper, jk, npiglo, npjglo, ktime=jt)
-        zsal( :,:) = getvar(cf_tfil, cn_vosaline, jk, npiglo, npjglo, ktime=jt)
+        ztemp(:,:) = getvar(cf_tfil, cv_tem, jk, npiglo, npjglo, ktime=jt)
+        zsal( :,:) = getvar(cf_tfil, cv_sal, jk, npiglo, npjglo, ktime=jt)
 
         WHERE( zsal == zspval ) zmask = 0
 
diff --git a/cdfsigintegr.f90 b/src/cdfsigintegr.f90
similarity index 100%
copy from cdfsigintegr.f90
copy to src/cdfsigintegr.f90
diff --git a/cdfsigintegr.f90 b/src/cdfsigintegr_bottom.f90
similarity index 77%
rename from cdfsigintegr.f90
rename to src/cdfsigintegr_bottom.f90
index d823778..9421327 100644
--- a/cdfsigintegr.f90
+++ b/src/cdfsigintegr_bottom.f90
@@ -1,6 +1,6 @@
-PROGRAM cdfsigintegr
+PROGRAM cdfsigintegr_bottom
   !!======================================================================
-  !!                     ***  PROGRAM  cdfsigintegr  ***
+  !!                     ***  PROGRAM  cdfsigintegr_bottom  ***
   !!=====================================================================
   !!  ** Purpose : This program is used to integrate quantities between 
   !!               isopycnals
@@ -11,6 +11,8 @@ PROGRAM cdfsigintegr
   !!               down to the given isopycnal. Finaly, by making the 
   !!               difference between 2 isopycnals we obtain the required 
   !!               quantity.
+  !!  **         : Modified by Pedro Colombo and Ignacio Merino in order 
+  !!               to make computation from the bottom 19/02/2015
   !!
   !! History : 2.1  : 12/2007  : J.M. Molines : Original code
   !!           3.0  : 06/2011  : J.M. Molines : Doctor norm + Lic.
@@ -20,7 +22,7 @@ PROGRAM cdfsigintegr
   USE modutils
   !!----------------------------------------------------------------------
   !! CDFTOOLS_3.0 , MEOM 2011
-  !! $Id$
+  !! $Id: cdfsigintegr.f90 657 2013-05-21 16:36:14Z molines $
   !! Copyright (c) 2011, J.-M. Molines
   !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
   !!----------------------------------------------------------------------
@@ -46,6 +48,7 @@ PROGRAM cdfsigintegr
   REAL(KIND=4), DIMENSION(:,:,:),   ALLOCATABLE :: zint             ! pseudo 3D working array (2)
   REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: v2d              ! 2D working array
   REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: e3               ! vertical metrics
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: eu               ! T horizontal metrics
   REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: tmask            ! mask of t points from rho
   REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: zdum             ! dummy array for I/O
   REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: rho_lev          ! value of isopycnals
@@ -54,6 +57,7 @@ PROGRAM cdfsigintegr
   REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: gdepw            ! depth of W points
   REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: e31d             ! vertical metrics in full step
   REAL(KIND=4)                                  :: zspval=999999.   ! output missing value
+  REAL(KIND=4)                                  :: maskvalue=0.     ! masked values for ocean velocity output
   REAL(KIND=4)                                  :: zspvalz          ! missing value from rho file      
 
   REAL(KIND=8), DIMENSION(:,:,:),   ALLOCATABLE :: dv2dint          ! interpolated value 
@@ -80,7 +84,7 @@ PROGRAM cdfsigintegr
 
   narg=iargc()
   IF ( narg < 3 ) THEN
-     PRINT *,' usage : cdfsigintegr IN-var RHO-file list_of_files [ VAR-type ] ...'
+     PRINT *,' usage : cdfsigintegr_bottom IN-var RHO-file list_of_files [ VAR-type ] ...'
      PRINT *,'              ... [ -sig sigma_name] [ -full ] '
      PRINT *,'      '
      PRINT *,'     PURPOSE :' 
@@ -109,7 +113,7 @@ PROGRAM cdfsigintegr
      PRINT *,'               integration. Default is ', TRIM(cf_rholev)
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
-     PRINT *,'       ', TRIM(cn_fzgr),' and ',TRIM(cf_rholev)
+     PRINT *,'       ', TRIM(cn_fzgr),',',TRIM(cn_fhgr),' and ',TRIM(cf_rholev)
      PRINT *,'      '
      PRINT *,'     OUTPUT : '
      PRINT *,'       netcdf file : IN-file.integr'
@@ -152,6 +156,7 @@ PROGRAM cdfsigintegr
 
   ! check for files
   lchk = lchk .OR. chkfile (cn_fzgr   )
+  lchk = lchk .OR. chkfile (cn_fhgr   )
   lchk = lchk .OR. chkfile (cf_rholev )
   lchk = lchk .OR. chkfile (cf_rho    )
   IF ( lchk ) STOP ! missing file
@@ -180,7 +185,7 @@ PROGRAM cdfsigintegr
   ALLOCATE(cv_names(nvars), stypzvar(nvars))
 
   cv_names(:)=getvarname(cf_in,nvars,stypzvar)
-
+  ALLOCATE( eu(npiglo,npjglo)) !Modified Pedro
   ALLOCATE( v3d(npiglo,npjglo,npk), dalpha(npiglo,npjglo,npiso), e3(npiglo,npjglo) )
   ALLOCATE( dv2dint(npiglo,npjglo,2), v2d(npiglo,npjglo), zint(npiglo,npjglo,2)  )
   ALLOCATE( h1d(npk) ,gdepw(npk) ,tmask(npiglo,npjglo), zdum(npiglo,npjglo) )
@@ -201,12 +206,23 @@ PROGRAM cdfsigintegr
      ENDIF
   END DO
 
+  !! Modified Pedro
+  ! Get horizontal grid
+  ! Obtain dx on t point
+  IF (ctype == 'U') THEN
+     eu(:,:) = getvar(cn_fhgr, cn_ve2t, 1, npiglo, npjglo)  
+  ELSE IF (ctype == 'V') THEN
+     eu(:,:) = getvar(cn_fhgr, cn_ve1t, 1, npiglo, npjglo)
+  END IF
+  
+  !! Commented Pedro
   !! ** Compute interpolation coefficients as well as the level used
-  !!    to interpolate between
+  !!    to nterpolate between
   DO ji=1,npiglo
      DO jj = 1, npjglo
         ijk = 1
-        DO jiso=1,npiso
+        !!DO jiso=1,npiso
+        jiso=1  !La primera definicion de isopyc la dejamos como esta
            !  Assume that rho (z) is increasing downward (no inversion)
            !     Caution with sigma0 at great depth !
            DO WHILE (rho_lev(jiso) >=  v3d(ji,jj,ijk) .AND. ijk <= npk &
@@ -215,20 +231,39 @@ PROGRAM cdfsigintegr
            END DO
            ijk = ijk-1
            ik0 = ijk
-           IF (ijk == 0) THEN
+           IF (ijk == 0) THEN !!At surface
               ijk = 1
               dalpha(ji,jj,jiso) = 0.d0
-           ELSE IF (v3d(ji,jj,ijk+1) == zspvalz ) THEN
+           ELSE IF (v3d(ji,jj,ijk+1) == zspvalz ) THEN !!Masked
               ik0 = 0
               dalpha(ji,jj,jiso) = 0.d0
            ELSE 
               ! ... dalpha is always in [0,1]. Adding ik0 ( >=1 ) for saving space for ik0
               dalpha(ji,jj,jiso)= (rho_lev(jiso)-v3d(ji,jj,ijk))/(v3d(ji,jj,ijk+1)-v3d(ji,jj,ijk)) + ik0
            ENDIF
-        END DO
+        !!END DO
      END DO
   END DO
 
+   
+   !! Commented Pedro
+   DO ji=1,npiglo
+     DO jj = 1, npjglo
+        ijk = 1
+        !!DO jiso=1,npiso
+        jiso=2  !La segunda definicion de isopyc la modificamos para extraer la superficie inferior
+           !  Assume that rho (z) is increasing downward (no inversion)
+           !     Caution with sigma0 at great depth ! 
+           maskvalue=v3d(ji,jj,npk) !We pick a value that we know is masked (last value)
+           DO WHILE (maskvalue /=  v3d(ji,jj,ijk) .AND. ijk <= npk ) !While the value is not masked, +1
+              ijk = ijk+1
+           END DO
+           ijk = ijk-1
+           dalpha(ji,jj,jiso) = ijk !Equal the first value before the mask appears
+        !!END DO
+     END DO
+ END DO
+   
   ! define header of all files
   ipk(1)=npiso-1 ; ipk(2)=npiso-1 ; ipk(3)=npiso ; ipk(4)=npiso-1
 
@@ -288,7 +323,7 @@ PROGRAM cdfsigintegr
      PRINT *,'working with ', TRIM(cf_in)
 
      ! create output file
-     cf_out=TRIM(cf_in)//'.integr'
+     cf_out='cdfsigintegr_file'
 
      ncout = create      (cf_out, cf_rho,  npiglo, npjglo, npiso                       )
      ierr  = createvar   (ncout,  stypvar, 4,      ipk,    id_varout, cdglobal=cglobal )
@@ -317,6 +352,7 @@ PROGRAM cdfsigintegr
               DO jj=2,npjglo
                  DO ji=1, npiglo
                     v3d(ji,jj,jk)=0.5*( v2d(ji,jj) + v2d(ji,jj-1) )  ! put variable on T point
+                    v3d(ji,1,jk)=0.5*( v2d(ji,2) + v2d(ji,1) )  ! put variable on T point
                  END DO
               END DO
            CASE('W','w' )
@@ -331,9 +367,10 @@ PROGRAM cdfsigintegr
               END DO
            END SELECT
         END DO
-
         ! Compute integral from surface to isopycnal
-        DO jiso=1,npiso
+        !! La primera integral la dejamos como esta
+        !!DO jiso=1,npiso
+        jiso=1 
            ! determine isopycnal surface
            DO ji=1,npiglo
               DO jj=1,npjglo
@@ -346,8 +383,25 @@ PROGRAM cdfsigintegr
                  ENDIF
               END DO
            END DO
+        ! Compute integral from surface to isopycnal
+        !! La segunda la modificamos
+        !!DO jiso=1,npiso
+        jiso=2
+           ! determine isopycnal surface
+           DO ji=1,npiglo
+              DO jj=1,npjglo
+                 ! ik0 is retrieved from dalpha, taking the integer part.
+                 ik0=INT(dalpha(ji,jj,jiso)) ; dalpha(ji,jj,jiso) =  dalpha(ji,jj,jiso) - ik0
+                 IF (zint(ji,jj,1) /= 0) THEN
+                    zint (ji,jj,2)=dalpha(ji,jj,jiso)*h1d(ik0+1) + (1.d0-dalpha(ji,jj,jiso))*h1d(ik0)
+                 ELSE 
+                    zint  (ji,jj,2)=0.  !zspval  
+                 ENDIF
+              END DO
+           END DO
            ! integrate from jk=1 to zint
            dv2dint(:,:,1) = 0.d0
+           dv2dint(:,:,2) = 0.d0
 
            DO jk=1,npk-1
               ! get metrixs at level jk
@@ -360,42 +414,57 @@ PROGRAM cdfsigintegr
               DO ji=1,npiglo
                  DO jj=1,npjglo
                     IF ( gdepw(jk)+e3(ji,jj) < zint(ji,jj,1) ) THEN  ! full cell
-                       dv2dint(ji,jj,1)=dv2dint(ji,jj,1) + e3(ji,jj)* v3d(ji,jj,jk)
+                       dv2dint(ji,jj,1)=dv2dint(ji,jj,1) + e3(ji,jj)* v3d(ji,jj,jk) * eu(ji,jj)
                     ELSE IF (( zint(ji,jj,1) <= gdepw(jk)+e3(ji,jj) ) .AND. (zint(ji,jj,1) > gdepw(jk)) ) THEN
-                       dv2dint(ji,jj,1)=dv2dint(ji,jj,1)+ (zint(ji,jj,1) - gdepw(jk) )* v3d(ji,jj,jk)
+                       dv2dint(ji,jj,1)=dv2dint(ji,jj,1)+ (zint(ji,jj,1) - gdepw(jk) )* v3d(ji,jj,jk) * eu(ji,jj)
                     ELSE   ! below the isopycnal 
                        ! do nothing for this i j point
                     ENDIF
                  END DO
               END DO
+ 
+              DO ji=1,npiglo
+                 DO jj=1,npjglo
+                    IF ( gdepw(jk)+e3(ji,jj) < zint(ji,jj,2) ) THEN  ! full cell
+                       dv2dint(ji,jj,2)=dv2dint(ji,jj,2) + e3(ji,jj)* v3d(ji,jj,jk) * eu(ji,jj)
+                    ELSE IF (( zint(ji,jj,2) <= gdepw(jk)+e3(ji,jj) ) .AND. (zint(ji,jj,2) > gdepw(jk)) ) THEN
+                       dv2dint(ji,jj,2)=dv2dint(ji,jj,2)+ (zint(ji,jj,2) - gdepw(jk) )* v3d(ji,jj,jk) * eu(ji,jj)
+                    ELSE   ! below the isopycnal 
+                       ! do nothing for this i j point
+                    ENDIF
+                 END DO
+              END DO
+
            END DO   ! end on vertical integral for isopynal jiso
 
-           zdum=zint(:,:,1)
+           !zdum=zint(:,:,1)
 
-           WHERE (tmask == 0. ) zdum=zspval
-           ierr = putvar(ncout,id_varout(3), zdum, jiso, npiglo, npjglo, ktime=jt )
+           WHERE (tmask == 0. ) zint(:,:,1)=zspval
+           WHERE (tmask == 0. ) zint(:,:,2)=zspval
+           ierr = putvar(ncout,id_varout(3), zint(:,:,1), 1, npiglo, npjglo, ktime=jt )
+           ierr = putvar(ncout,id_varout(3), zint(:,:,2), 2, npiglo, npjglo, ktime=jt )
 
-           IF (jiso > 1  ) THEN  ! compute the difference ie the inventory in the layer between 2 isopycnals
-              zdum=dv2dint(:,:,1) - dv2dint(:,:,2) ; WHERE ((tmask == 0.)  .OR. (zdum < 0 ) ) zdum = zspval
-              ierr = putvar(ncout, id_varout(1), zdum, jiso-1, npiglo, npjglo, ktime=jt)
+           !IF (jiso > 1  ) THEN  ! compute the difference ie the inventory in the layer between 2 isopycnals
+           zdum=dv2dint(:,:,2) - dv2dint(:,:,1) ; WHERE (tmask == 0.) zdum = zspval
+           ierr = putvar(ncout, id_varout(1), zdum, 1, npiglo, npjglo, ktime=jt)
 
-              zdum=zint  (:,:,1) - zint  (:,:,2) ; WHERE ((tmask == 0.)  .OR. (zdum < 0 ) ) zdum = zspval
-              ierr = putvar(ncout, id_varout(2), zdum, jiso-1, npiglo, npjglo, ktime=jt)
+           zdum=zint  (:,:,2) - zint  (:,:,1) ; WHERE (tmask == 0.) zdum = zspval
+           ierr = putvar(ncout, id_varout(2), zdum, 1, npiglo, npjglo, ktime=jt)
 
-              WHERE ( zdum /= zspval .AND. zdum /= 0.) 
-                 zdum=(dv2dint(:,:,1) - dv2dint(:,:,2))/ zdum
-              ELSEWHERE
-                 zdum=zspval
-              ENDWHERE
-              ierr = putvar(ncout, id_varout(4), zdum, jiso-1, npiglo, npjglo, ktime=jt)
+           WHERE ( zdum /= zspval .AND. zdum /= 0.) 
+              zdum=(dv2dint(:,:,2) - dv2dint(:,:,1))/ zdum
+           ELSEWHERE
+              zdum=zspval
+           ENDWHERE
+           ierr = putvar(ncout, id_varout(4), zdum, jiso-1, npiglo, npjglo, ktime=jt)
 
-           ENDIF
-           dv2dint(:,:,2) = dv2dint(:,:,1)
-           zint   (:,:,2) = zint   (:,:,1)
+           !ENDIF
+           !dv2dint(:,:,2) = dv2dint(:,:,1)
+           !zint   (:,:,2) = zint   (:,:,1)
 
         END DO
-     END DO
+     !END DO
      ierr = closeout(ncout)
   END DO  ! loop on scalar files
   PRINT *,' integral between isopycnals completed successfully'
-END  PROGRAM cdfsigintegr
+END  PROGRAM cdfsigintegr_bottom
diff --git a/src/cdfsigintegr_pedro.f90 b/src/cdfsigintegr_pedro.f90
new file mode 100644
index 0000000..6d57d84
--- /dev/null
+++ b/src/cdfsigintegr_pedro.f90
@@ -0,0 +1,578 @@
+PROGRAM cdfsigintegr_pedro
+  !!======================================================================
+  !!                     ***  PROGRAM  cdfsigintegr  ***
+  !!=====================================================================
+  !!  ** Purpose : This program is used to integrate quantities between 
+  !!               isopycnals
+  !!
+  !!  ** Method  : Linear interpolation is used on the vertical to define
+  !!               the depth of the given isopycn.
+  !!               Then, the integral is performed from the top of the ocean
+  !!               down to the given isopycnal. Finaly, by making the 
+  !!               difference between 2 isopycnals we obtain the required 
+  !!               quantity.
+  !!
+  !! History : 2.1  : 12/2007  : J.M. Molines : Original code
+  !!           3.0  : 06/2011  : J.M. Molines : Doctor norm + Lic.
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE modcdfnames
+  USE modutils
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id: cdfsigintegr.f90 657 2013-05-21 16:36:14Z molines $
+  !! Copyright (c) 2011, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)                               :: ji, jj, jk, jt   ! dummy loop index
+  INTEGER(KIND=4)                               :: jiso, jfich      ! dummy loop index
+  INTEGER(KIND=4)                               :: jvar             ! dummy loop index
+  INTEGER(KIND=4)                               :: npiglo, npjglo   ! domain size
+  INTEGER(KIND=4)                               :: npk, npt         ! domain size
+  INTEGER(KIND=4)                               :: npiso, nvars     ! number of isopycnals, variables
+  INTEGER(KIND=4)                               :: narg, iargc      ! command line
+  INTEGER(KIND=4)                               :: ijarg, ireq      ! command line
+  INTEGER(KIND=4)                               :: nfiles           ! number of input files
+  INTEGER(KIND=4)                               :: istrt_arg        ! argument number of first input file
+  INTEGER(KIND=4)                               :: ik0              ! layer index
+  INTEGER(KIND=4)                               :: ijk              ! layer index
+  INTEGER(KIND=4)                               :: numin=10         ! logical unit for ascii input file
+  INTEGER(KIND=4)                               :: ncout, ierr      ! ncid and status variable
+  INTEGER(KIND=4), DIMENSION(9)                 :: ipk, id_varout   ! levels and id's of output variables
+  !
+  REAL(KIND=4), DIMENSION(:,:,:),   ALLOCATABLE :: v3d              ! 3D v working array (npk)
+  REAL(KIND=4), DIMENSION(:,:,:),   ALLOCATABLE :: u3d              ! 3D u working array (npk)
+  REAL(KIND=4), DIMENSION(:,:,:),   ALLOCATABLE :: m3d              ! 3D modulus working array (npk)
+  REAL(KIND=4), DIMENSION(:,:,:),   ALLOCATABLE :: zint             ! pseudo 3D working array (2)
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: v2d              ! 2D v working array
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: u2d              ! 2D u working array
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: e3               ! vertical metrics
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: e1t              ! U/V Horizontal metric !!Pedro
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: e2t              ! U/V Horizontal metric !!Pedro
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: tmask            ! mask of t points from rho
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: zdum             ! dummy array for I/O
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: zdum_u           ! dummy array for I/O for u
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: zdum_v           ! dummy array for I/O for v
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: zdum_m           ! dummy array for I/O for m
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: zdum_a           ! dummy array for I/O for angle
+  REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: rho_lev          ! value of isopycnals
+  REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: tim              ! time counter
+  REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: h1d              ! depth of rho points
+  REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: gdepw            ! depth of W points
+  REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: e31d             ! vertical metrics in full step
+  REAL(KIND=4)                                  :: zspval=999999.   ! output missing value
+  REAL(KIND=4)                                  :: zspvalz          ! missing value from rho file      
+  REAL(KIND=4)                                  :: maskvalue=0.     ! masked values for ocean velocity output
+  INTEGER(KIND=4)                               :: nboutput=9       ! number of values to write in cdf output
+  REAL(KIND=4)                                  :: pi               !pi 
+
+  REAL(KIND=8), DIMENSION(:,:,:),   ALLOCATABLE :: dv2dint          ! interpolated value / int of v 
+  REAL(KIND=8), DIMENSION(:,:,:),   ALLOCATABLE :: du2dint          ! int of u
+  REAL(KIND=8), DIMENSION(:,:,:),   ALLOCATABLE :: dm2dint          ! int of the modulus
+  REAL(KIND=8), DIMENSION(:,:,:),   ALLOCATABLE :: dalpha           ! 3D coefficient (npiso)
+
+  CHARACTER(LEN=256)                            :: cf_rholev = 'rho_lev' ! input file for rho surfaces
+  CHARACTER(LEN=256)                            :: cf_ufil          ! input file for u data
+  CHARACTER(LEN=256)                            :: cf_vfil          ! input file for v data
+  CHARACTER(LEN=256)                            :: cf_rho           ! input file for density
+  CHARACTER(LEN=256)                            :: cf_out           ! output file
+  CHARACTER(LEN=256)                            :: cv_in            ! name of input variable
+  CHARACTER(LEN=256)                            :: cldum            ! dummy string variable
+  CHARACTER(LEN=256)                            :: cluni            ! dummy string variable for variable units
+  CHARACTER(LEN=256)                            :: cglobal          ! global attribute
+  CHARACTER(LEN=256)                            :: ctype='T'        ! position of variable on C grid
+  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_names         ! temporary arry for variable name in file
+
+  TYPE(variable), DIMENSION(:),     ALLOCATABLE :: stypvar          ! structure for attributes
+  TYPE(variable), DIMENSION(:),     ALLOCATABLE :: stypzvar         ! structure for attributes
+
+  LOGICAL                                       :: lfull = .FALSE.  ! flag for full step
+  LOGICAL                                       :: lchk  = .FALSE.  ! flag for missing files
+  !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  narg=iargc()
+  IF ( narg < 3 ) THEN
+     PRINT *,' usage : cdfsigintegr IN-var RHO-file list_of_files [ VAR-type ] ...'
+     PRINT *,'              ... [ -sig sigma_name] [ -full ] '
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :' 
+     PRINT *,'       Take a list of input files with specific IN-var variable, associated'
+     PRINT *,'       with a reference density file. A set of isopycnal surfaces is defined'
+     PRINT *,'       in an ASCII file (rho_lev by default), using same depth reference than'
+     PRINT *,'       the input reference density file. This program computes the integral of'
+     PRINT *,'       IN-var between the isopycnals defined in rho_lev. It also gives the '
+     PRINT *,'       isopycnal depth and thickness of density layers.'
+     PRINT *,'      '
+     PRINT *,'       Rho_lev file first line indicates the number of following isopycnals.'
+     PRINT *,'       Then a list of the densities is given, one per line.'
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       IN-var : input variable to be integrated' 
+     PRINT *,'       RHO-file : netcdf file with already computed density' 
+     PRINT *,'       list_of_files : a list of model netcdf files containing IN-var.'
+     PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'       [ VAR-type ] : one of T U V F W which defined the position on' 
+     PRINT *,'               IN-var in the model C-grid. Default is ', TRIM(ctype)
+     PRINT *,'       [ -sig sigma_name ] : give the name of sigma variable in RHO-file.'
+     PRINT *,'               Default is ',TRIM(cn_vosigma0)
+     PRINT *,'       [ -full ] : indicate a full step configuration.'
+     PRINT *,'       [ -rholev  file] : indicates name of file defining the limits for '
+     PRINT *,'               integration. Default is ', TRIM(cf_rholev)
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'       ', TRIM(cn_fzgr),',',TRIM(cn_fhgr),' and ',TRIM(cf_rholev)
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file : IN-file.integr'
+     PRINT *,'         variables : inv_IN-var  : inventory of IN-var from input file.'
+     PRINT *,'                     ', TRIM(cn_vodepiso),' (m) : depth of isopycnal.'
+     PRINT *,'                     ', TRIM(cn_isothick),' (m) : thickness of isopycnal layer.'
+     PRINT *,'                     mean_IN-var (same unit as IN-var) : mean IN-var in the isopycnal'
+     PRINT *,'      '
+     PRINT *,'     SEE ALSO :'
+     PRINT *,'      cdfrhoproj, cdfsigtrp, cdfisopycdep'
+     PRINT *,'      '
+     STOP
+  ENDIF
+  pi=ACOS(-1.)
+  !ijarg = 1 ; ireq = 0 ; nfiles = 0
+  ijarg = 1 ; ireq = 0
+  DO WHILE ( ijarg <= narg ) 
+     CALL getarg( ijarg, cldum ) ; ijarg = ijarg+1
+     SELECT CASE ( cldum )
+     !CASE ( 'T','t','U','u','V','v','F','f','W','w' )
+        !ctype=cldum
+     CASE ( '-sig '   ) ; CALL getarg( ijarg, cn_vosigma0) ; ijarg = ijarg+1
+     CASE ( '-rholev ') ; CALL getarg( ijarg, cf_rholev  ) ; ijarg = ijarg+1
+     CASE ( '-full '  ) ; lfull = .TRUE.
+     CASE DEFAULT
+        ireq=ireq+1
+        SELECT CASE ( ireq )
+        CASE ( 1 ) ; cf_rho = cldum
+        CASE ( 2 ) ; cf_ufil  = cldum
+        CASE ( 3 ) ; cf_vfil = cldum
+        CASE DEFAULT 
+           !nfiles=nfiles+1
+           !IF ( nfiles == 1 ) istrt_arg = ijarg - 1
+           PRINT *,' Too many arguments ' ; STOP
+        END SELECT
+     END SELECT
+  END DO
+
+  CALL SetGlobalAtt( cglobal )
+
+  ! check for files existence
+  lchk = lchk .OR. chkfile (cn_fzgr   )
+  lchk = lchk .OR. chkfile (cn_fhgr   ) !!Modified Pedro (Added)
+  lchk = lchk .OR. chkfile (cf_rholev )
+  lchk = lchk .OR. chkfile (cf_rho    )
+  lchk = lchk .OR. chkfile (cf_ufil   )
+  lchk = lchk .OR. chkfile (cf_vfil   )
+  IF ( lchk ) STOP ! missing file
+
+  ! Read rho level between which the integral is being performed
+  OPEN(numin,file=cf_rholev)
+  READ(numin,*) npiso
+  ALLOCATE (rho_lev(npiso) )
+  PRINT *,' Density limits read in ',TRIM(cf_rholev)
+  DO jiso=1,npiso
+     READ(numin,*) rho_lev(jiso)
+     PRINT *,rho_lev(jiso)
+  END DO
+  CLOSE(numin)
+
+  npiglo = getdim(cf_rho, cn_x)
+  npjglo = getdim(cf_rho, cn_y)
+  npk    = getdim(cf_rho, cn_z)
+  
+  zspvalz=getspval(cf_rho, cn_vosigma0)
+
+  !CALL getarg(istrt_arg, cf_ufil)
+  !IF ( chkfile ( cf_ufil ) ) STOP ! missing file
+
+  nvars=getnvar(cf_vfil)
+  ALLOCATE(cv_names(nvars), stypzvar(nvars))
+
+  cv_names(:)=getvarname(cf_vfil,nvars,stypzvar)
+  ALLOCATE( e1t(npiglo,npjglo), e2t(npiglo,npjglo) ) !!Modified Pedro (added)
+  ALLOCATE( v3d(npiglo,npjglo,npk), u3d(npiglo,npjglo,npk), m3d(npiglo,npjglo,npk), u2d(npiglo,npjglo))
+  ALLOCATE(dalpha(npiglo,npjglo,npiso), e3(npiglo,npjglo) )
+  ALLOCATE( dv2dint(npiglo,npjglo,2), v2d(npiglo,npjglo), zint(npiglo,npjglo,2)  )
+  ALLOCATE( du2dint(npiglo,npjglo,2), dm2dint(npiglo,npjglo,2))
+  ALLOCATE( h1d(npk) ,gdepw(npk) ,tmask(npiglo,npjglo), zdum_u(npiglo,npjglo) )
+  ALLOCATE( zdum_v(npiglo,npjglo), zdum_m(npiglo,npjglo), zdum(npiglo,npjglo) )
+  ALLOCATE( stypvar(nboutput) , zdum_a(npiglo,npjglo) )
+  IF ( lfull ) ALLOCATE ( e31d(npk) )
+
+  gdepw(:) = getvare3(cn_fzgr, cn_gdepw, npk)
+
+  IF (lfull ) e31d(:) = getvare3(cn_fzgr, cn_ve3t, npk)
+
+  h1d(:) = getvar1d(cf_rho, cn_vdeptht, npk)
+
+  ! Note, if working with vertical slabs, one may avoid 3D array, but may be slow ...
+  tmask=1.
+  DO jk=1,npk
+     v3d(:,:,jk) = getvar(cf_rho, cn_vosigma0, jk, npiglo, npjglo)
+     IF ( jk == 1 ) THEN
+        WHERE (v3d(:,:,jk) == zspvalz ) tmask=0.
+     ENDIF
+  END DO
+
+  !! Modified Pedro
+  !! Get horizontal grid
+  !! Obtain dx on t point
+  !IF (ctype == 'U') THEN
+  e2t(:,:)   = getvar(cn_fhgr, cn_ve2t, 1, npiglo, npjglo)
+  !! Obtain dy on t point
+  !ELSE IF (ctype == 'V') THEN
+  e1t(:,:)   = getvar(cn_fhgr, cn_ve1t, 1, npiglo, npjglo)
+  !! end modifying
+  !END IF
+
+  !! ** Compute interpolation coefficients as well as the level used
+  !!    to interpolate between
+  !! Comented Pedro
+  DO ji=1,npiglo
+     DO jj = 1, npjglo
+        ijk = 1
+        !!DO jiso=1,npiso 
+        jiso=1 !! La primera definicion de isopyc la dejamos como esta
+           !  Assume that rho (z) is increasing downward (no inversion)
+           !     Caution with sigma0 at great depth !
+           DO WHILE (rho_lev(jiso) >=  v3d(ji,jj,ijk) .AND. ijk <= npk &
+                &                .AND. v3d(ji,jj,ijk) /=  zspvalz )
+              ijk = ijk+1
+           END DO
+           ijk = ijk-1
+           ik0 = ijk
+           IF (ijk == 0) THEN
+              ijk = 1
+              dalpha(ji,jj,jiso) = 0.d0
+           ELSE IF (v3d(ji,jj,ijk+1) == zspvalz ) THEN !!Masked values
+              ik0 = 0
+              dalpha(ji,jj,jiso) = 0.d0
+           ELSE 
+              ! ... dalpha is always in [0,1]. Adding ik0 ( >=1 ) for saving space for ik0
+              dalpha(ji,jj,jiso)= (rho_lev(jiso)-v3d(ji,jj,ijk))/(v3d(ji,jj,ijk+1)-v3d(ji,jj,ijk)) + ik0
+           ENDIF
+        !!END DO
+     END DO
+  END DO
+
+      !! Commented Pedro
+   DO ji=1,npiglo
+      DO jj = 1, npjglo
+         ijk = 1
+         !!DO jiso=1,npiso
+         jiso=2  !La segunda definicion de isopyc la modificamos para extraer la superficie inferior
+            !  Assume that rho (z) is increasing downward (no inversion)
+            !     Caution with sigma0 at great depth ! 
+            maskvalue=v3d(ji,jj,npk) !We pick a value that we know is masked (last value)
+            DO WHILE (maskvalue /=  v3d(ji,jj,ijk) .AND. ijk <= npk ) !While the value is not masked, +1
+               ijk = ijk+1
+            END DO
+            ijk = ijk-1
+            dalpha(ji,jj,jiso) = ijk !Equal the first value before the mask appears
+         !!END DO
+      END DO
+  END DO
+
+  ! define header of all files
+  ipk(1)=npiso-1 ; ipk(2)=npiso-1 ; ipk(3)=npiso ; ipk(4)=npiso-1
+  ipk(5)=npiso-1 ; ipk(6)=npiso-1 ; ipk(7)=npiso-1 ; ipk(8)=npiso-1 
+  ipk(9)=npiso-1
+  !DO jvar=1,nvars
+  !   IF ( cv_in == stypzvar(jvar)%cname ) THEN 
+  !      stypvar(1)=stypzvar(jvar)
+  !      EXIT
+  !   ENDIF
+  !END DO
+  ! save original long name for further process
+  !cldum = TRIM(stypvar(1)%clong_name)
+  !cluni = TRIM(cv_vomecrty%cunits)
+
+  stypvar(1)%cname             = 'int_vomecrty'
+  stypvar(1)%clong_name        = 'vomecrty integrated on sigma bin'
+  stypvar(1)%cshort_name       = stypvar(1)%cname
+  stypvar(1)%cunits            = 'Sv'
+  stypvar(1)%rmissing_value    = zspval
+  stypvar(1)%caxis             = 'TRYX'
+
+  stypvar(2)%cname             = TRIM(cn_isothick)
+  stypvar(2)%cunits            = 'm'
+  stypvar(2)%rmissing_value    = zspval
+  stypvar(2)%valid_min         = 0.
+  stypvar(2)%valid_max         = 7000.
+  stypvar(2)%clong_name        = 'Thickness_of_Isopycnals'
+  stypvar(2)%cshort_name       = TRIM(cn_isothick)
+  stypvar(2)%conline_operation = 'N/A'
+  stypvar(2)%caxis             = 'TRYX'
+
+  stypvar(3)%cname             = TRIM(cn_vodepiso)
+  stypvar(3)%cunits            = 'm'
+  stypvar(3)%rmissing_value    = zspval
+  stypvar(3)%valid_min         = 0.
+  stypvar(3)%valid_max         = 7000.
+  stypvar(3)%clong_name        = 'Depth_of_Isopycnals'
+  stypvar(3)%cshort_name       = TRIM(cn_vodepiso)
+  stypvar(3)%conline_operation = 'N/A'
+  stypvar(3)%caxis             = 'TRYX'
+
+  stypvar(4)%cname             = 'mean_vomecrty'
+  stypvar(4)%cunits            = 'm/s'
+  stypvar(4)%rmissing_value    = zspval
+  stypvar(4)%valid_min         = stypvar(1)%valid_min
+  stypvar(4)%valid_max         = stypvar(1)%valid_min
+  stypvar(4)%clong_name        = ' mean value in sigma layer'
+  stypvar(4)%cshort_name       = stypvar(4)%cname
+  stypvar(4)%conline_operation = 'N/A'
+  stypvar(4)%caxis             = 'TRYX'
+
+  stypvar(5)%cname             = 'int_vozocrtx'
+  stypvar(5)%clong_name        = ' vozocrtx integrated on sigma bin'
+  stypvar(5)%cshort_name       = stypvar(5)%cname
+  stypvar(5)%cunits            = 'Sv'
+  stypvar(5)%rmissing_value    = zspval
+  stypvar(5)%caxis             = 'TRYX'
+
+  stypvar(6)%cname             = 'mean_vozocrtx'
+  stypvar(6)%cunits            = 'm/s'
+  stypvar(6)%rmissing_value    = zspval
+  stypvar(6)%valid_min         = stypvar(5)%valid_min
+  stypvar(6)%valid_max         = stypvar(5)%valid_min
+  stypvar(6)%clong_name        = 'mean value in sigma layer'
+  stypvar(6)%cshort_name       = stypvar(6)%cname
+  stypvar(6)%conline_operation = 'N/A'
+  stypvar(6)%caxis             = 'TRYX'
+  
+  stypvar(7)%cname             = 'int_modulus'
+  stypvar(7)%clong_name        = 'integration of the modulus'
+  stypvar(7)%cshort_name       = stypvar(7)%cname
+  stypvar(7)%cunits            = 'Sv'
+  stypvar(7)%rmissing_value    = zspval
+  stypvar(7)%caxis             = 'TRYX'
+
+  stypvar(8)%cname             = 'modulus_mean' 
+  stypvar(8)%cunits            = 'm/s'
+  stypvar(8)%rmissing_value    = zspval
+  stypvar(8)%valid_min         = stypvar(7)%valid_min
+  stypvar(8)%valid_max         = stypvar(7)%valid_min
+  stypvar(8)%clong_name        = 'mean value of the modulus in sigma layer'
+  stypvar(8)%cshort_name       = stypvar(8)%cname
+  stypvar(8)%conline_operation = 'N/A'
+  stypvar(8)%caxis             = 'TRYX'
+  
+  stypvar(9)%cname             = 'angle_modulus'
+  stypvar(9)%clong_name        = 'Modulus angle'
+  stypvar(9)%cshort_name       = stypvar(9)%cname
+  stypvar(9)%cunits            = '°'
+  stypvar(9)%rmissing_value    = zspval
+  stypvar(9)%caxis             = 'TRYX'
+
+!! ** Loop on the scalar files to project on choosen isopycnics surfaces
+  !DO jfich=1, nfiles
+
+     !CALL getarg(jfich+istrt_arg-1, cf_ufil)
+     !IF ( chkfile (cf_ufil) ) STOP ! missing file
+     !IF ( chkfile (cf_vfil) ) STOP ! missing file
+     PRINT *,'working with ', TRIM(cf_ufil)
+     PRINT *,'working with ', TRIM(cf_vfil)
+
+     ! create output file
+     !! Modified Pedro
+     !cf_out=TRIM(cf_in)//'.integr'
+     cf_out='cdfsigintegr_file'
+     ncout = create      (cf_out, cf_rho,  npiglo, npjglo, npiso                       )
+     ierr  = createvar   (ncout,  stypvar, 9,      ipk,    id_varout, cdglobal=cglobal )
+     ierr  = putheadervar(ncout,  cf_rho,  npiglo, npjglo, npiso, pdep=rho_lev         )
+     ! copy time arrays in output file
+     npt = getdim ( cf_ufil, cn_t)
+     ALLOCATE ( tim(npt) )
+     tim(:) = getvar1d(cf_ufil, cn_vtimec, npt     )
+     ierr   = putvar1d(ncout, tim,       npt, 'T')
+     DEALLOCATE ( tim )
+     DO jt =1, npt
+        DO jk=1,npk
+           v2d(:,:) = getvar(cf_vfil, cn_vomecrty, jk, npiglo, npjglo, ktime = jt )
+           u2d(:,:) = getvar(cf_ufil, cn_vozocrtx, jk, npiglo, npjglo, ktime = jt )
+           !SELECT CASE ( ctype )
+           !CASE ('T', 't' )
+           !   v3d(:,:,jk) = v2d(:,:)
+           !CASE ('U','u' )
+              DO jj=1,npjglo
+                 DO ji=2, npiglo
+                    u3d(ji,jj,jk)=0.5*( u2d(ji,jj) + u2d(ji-1,jj) )  ! put variable on T point
+                    u3d(1,jj,jk)=0.5*( u2d(2,jj) + u2d(1,jj) )  ! put variable on T point
+                 END DO
+              END DO
+           !CASE ('V','v' )
+              DO jj=2,npjglo
+                 DO ji=1, npiglo
+                    v3d(ji,jj,jk)=0.5*( v2d(ji,jj) + v2d(ji,jj-1) )  ! put variable on T point
+                    v3d(ji,1,jk)=0.5*( v2d(ji,2) + v2d(ji,1) )  ! put variable on T point
+                 END DO
+              END DO              
+           !CASE('W','w' )
+              !v3d(:,:,jk) = v2d(:,:)
+              !v2d(:,:) = getvar(cf_ufil, cv_in, jk+1, npiglo, npjglo, ktime = jt )
+              !v3d(:,:,jk) = 0.5 * ( v3d(:,:,jk) + v2d(:,:) )
+           !CASE('F','f' )
+              !DO jj = 2, npjglo
+                 !DO ji = 2, npiglo
+                    !v3d(:,:,jk) = 0.25*( v2d(ji,jj) + v2d( ji, jj-1) + v2d (ji-1,jj-1) + v2d(ji-1, jj) )
+                 !END DO
+              !END DO
+           !END SELECT
+        END DO
+
+        ! Compute integral from surface to isopycnal
+        !!DO jiso=1,npiso
+        jiso=1 !! La primera integral la dejamos como esta
+           ! determine isopycnal surface
+           DO ji=1,npiglo
+              DO jj=1,npjglo
+                 ! ik0 is retrieved from dalpha, taking the integer part.
+                 ik0=INT(dalpha(ji,jj,jiso)) ; dalpha(ji,jj,jiso) =  dalpha(ji,jj,jiso) - ik0
+                 IF (ik0 /= 0) THEN
+                    zint (ji,jj,1)=dalpha(ji,jj,jiso)*h1d(ik0+1) + (1.d0-dalpha(ji,jj,jiso))*h1d(ik0)
+                 ELSE 
+                    zint  (ji,jj,1)=0. !zspval
+                 ENDIF
+              END DO
+           END DO
+
+        ! Compute integral from surface to isopycnal
+        jiso=2 !! En la segunda utilizamos la batimetria
+           ! determine isopycnal surface
+           DO ji=1,npiglo
+              DO jj=1,npjglo
+                 ! ik0 is retrieved from dalpha, taking the integer part.
+                 ik0=INT(dalpha(ji,jj,jiso)) ; dalpha(ji,jj,jiso) =  dalpha(ji,jj,jiso) - ik0
+                 IF (zint(ji,jj,1) /= 0) THEN
+                    zint (ji,jj,2)=dalpha(ji,jj,jiso)*h1d(ik0+1) + (1.d0-dalpha(ji,jj,jiso))*h1d(ik0)
+                 ELSE
+                    zint  (ji,jj,2)=0. !zspval
+                 ENDIF
+              END DO
+           END DO
+           ! integrate from jk=1 to zint
+           du2dint(:,:,1) = 0.d0
+           du2dint(:,:,2) = 0.d0
+           dv2dint(:,:,1) = 0.d0
+           dv2dint(:,:,2) = 0.d0
+           dm2dint(:,:,1) = 0.d0
+           dm2dint(:,:,2) = 0.d0
+
+           DO jk=1,npk-1
+              ! get metrixs at level jk
+              IF ( lfull ) THEN 
+                 e3(:,:) = e31d(jk)
+              ELSE
+                 e3(:,:)=getvar(cn_fzgr,'e3t_ps',jk,npiglo,npjglo,ldiom=.TRUE.)
+              ENDIF
+
+              DO ji=1,npiglo
+                 DO jj=1,npjglo
+                    IF ( gdepw(jk)+e3(ji,jj) < zint(ji,jj,1) ) THEN  ! full cell
+                       !!dv2dint(ji,jj,1)=dv2dint(ji,jj,1) + e3(ji,jj)* v3d(ji,jj,jk)
+                       du2dint(ji,jj,1)=du2dint(ji,jj,1) + e3(ji,jj)* u3d(ji,jj,jk) * e2t(ji,jj) / 1000000 !!Modified Pedro
+                       dv2dint(ji,jj,1)=dv2dint(ji,jj,1) + e3(ji,jj)* v3d(ji,jj,jk) * e1t(ji,jj) / 1000000!!Modified Pedro
+                       !dm2dint(ji,jj,1)=dm2dint(ji,jj,1) + SQRT(du2dint(ji,jj,1)*du2dint(ji,jj,1) + &
+                       !                                   & dv2dint(ji,jj,1)*dv2dint(ji,jj,1))
+                    ELSE IF (( zint(ji,jj,1) <= gdepw(jk)+e3(ji,jj) ) .AND. (zint(ji,jj,1) > gdepw(jk)) ) THEN
+                       !!dv2dint(ji,jj,1)=dv2dint(ji,jj,1)+ (zint(ji,jj,1) - gdepw(jk) )* v3d(ji,jj,jk)
+                       du2dint(ji,jj,1)=du2dint(ji,jj,1)+ (zint(ji,jj,1) - gdepw(jk) )* u3d(ji,jj,jk) * e2t(ji,jj) / 1000000!! Modified Pedro
+                       dv2dint(ji,jj,1)=dv2dint(ji,jj,1)+ (zint(ji,jj,1) - gdepw(jk) )* v3d(ji,jj,jk) * e1t(ji,jj) / 1000000!! Modified Pedro
+                       !dm2dint(ji,jj,1)=dm2dint(ji,jj,1)+ (zint(ji,jj,1) - gdepw(jk) )* SQRT(du2dint(ji,jj,1)* &
+                       !                 & du2dint(ji,jj,1) + dv2dint(ji,jj,1)*dv2dint(ji,jj,1)) !! Modified Pedro
+                    ELSE   ! below the isopycnal 
+                       ! do nothing for this i j point
+                    ENDIF
+                 END DO
+              END DO
+              
+              DO ji=1,npiglo
+                 DO jj=1,npjglo
+                    IF ( gdepw(jk)+e3(ji,jj) < zint(ji,jj,2) ) THEN  ! full cell
+                       !!dv2dint(ji,jj,1)=dv2dint(ji,jj,1) + e3(ji,jj)* v3d(ji,jj,jk)
+                       du2dint(ji,jj,2)=du2dint(ji,jj,2) + e3(ji,jj)* u3d(ji,jj,jk) * e2t(ji,jj) / 1000000
+                       dv2dint(ji,jj,2)=dv2dint(ji,jj,2) + e3(ji,jj)* v3d(ji,jj,jk) * e1t(ji,jj) / 1000000!!Modified Pedro
+                       !dm2dint(ji,jj,2)=dm2dint(ji,jj,2) + SQRT(du2dint(ji,jj,2)*du2dint(ji,jj,2) + &
+                       !                                    & dv2dint(ji,jj,2)*dv2dint(ji,jj,2))
+                    ELSE IF (( zint(ji,jj,2) <= gdepw(jk)+e3(ji,jj) ) .AND. (zint(ji,jj,2) > gdepw(jk)) ) THEN
+                       !!dv2dint(ji,jj,1)=dv2dint(ji,jj,1)+ (zint(ji,jj,1) - gdepw(jk) )* v3d(ji,jj,jk)
+                       du2dint(ji,jj,2)=du2dint(ji,jj,2)+ (zint(ji,jj,2) - gdepw(jk) )* u3d(ji,jj,jk) * e2t(ji,jj) / 1000000!! Modified Pedro
+                       dv2dint(ji,jj,2)=dv2dint(ji,jj,2)+ (zint(ji,jj,2) - gdepw(jk) )* v3d(ji,jj,jk) * e1t(ji,jj) / 1000000!! Modified Pedro
+                       !dm2dint(ji,jj,2)=dm2dint(ji,jj,2)+ (zint(ji,jj,2) - gdepw(jk) )* SQRT(du2dint(ji,jj,2)* &
+                       !                 & du2dint(ji,jj,2) + dv2dint(ji,jj,2)*dv2dint(ji,jj,2))!! Modified Pedro
+                    ELSE   ! below the isopycnal 
+                       ! do nothing for this i j point
+                    ENDIF
+                 END DO
+              END DO
+           END DO   ! end on vertical integral for isopynal jiso
+
+           zdum=zint(:,:,1)
+
+           WHERE (tmask == 0. ) zint(:,:,1)=zspval
+           WHERE (tmask == 0. ) zint(:,:,2)=zspval
+           !ierr = putvar(ncout,id_varout(3), zdum, jiso, npiglo, npjglo, ktime=jt ) !Saves depth of isopycnals
+           ierr = putvar(ncout,id_varout(3), zint(:,:,1), 1, npiglo, npjglo, ktime=jt )
+           ierr = putvar(ncout,id_varout(3), zint(:,:,2), 2, npiglo, npjglo, ktime=jt )
+
+           !IF (jiso > 1  ) THEN  ! compute the difference ie the inventory in the layer between 2 isopycnals
+              !zdum=dv2dint(:,:,1) - dv2dint(:,:,2) ; WHERE ((tmask == 0.)  .OR. (zdum < 0 ) ) zdum = zspval
+           zdum_u=du2dint(:,:,2) - du2dint(:,:,1) ; WHERE (tmask == 0. ) zdum_u = zspval !! Modified Pedro
+           zdum_v=dv2dint(:,:,2) - dv2dint(:,:,1) ; WHERE (tmask == 0. ) zdum_v = zspval !! Modified Pedro
+           zdum_m=dm2dint(:,:,2) - dm2dint(:,:,1) ; WHERE (tmask == 0. ) zdum_m = zspval !! Modified Pedro
+              !ierr = putvar(ncout, id_varout(1), zdum, jiso-1, npiglo, npjglo, ktime=jt) !Saves integral
+           ierr = putvar(ncout, id_varout(5), zdum_u, 1, npiglo, npjglo, ktime=jt)
+           ierr = putvar(ncout, id_varout(1), zdum_v, 1, npiglo, npjglo, ktime=jt)
+           !ierr = putvar(ncout, id_varout(7), zdum_m, 1, npiglo, npjglo, ktime=jt)
+     
+           DO ji=1,npiglo
+              DO jj=1,npjglo
+                 zdum_m(ji,jj) = SQRT(zdum_v(ji,jj) * zdum_v(ji,jj) + zdum_u(ji,jj) * zdum_u(ji,jj))
+                 zdum_a(ji,jj)= atan2(zdum_v(ji,jj), zdum_u(ji,jj)) * 180./pi 
+                 IF ( zdum_v(ji,jj) < 0. ) zdum_a(ji,jj) = 360.+zdum_a(ji,jj)
+              END DO
+           END DO
+           WHERE (tmask == 0. ) zdum_m=zspval
+           WHERE (tmask == 0. ) zdum_a = zspval
+           ierr = putvar(ncout, id_varout(7), zdum_m, 1, npiglo, npjglo, ktime=jt)
+           ierr = putvar(ncout, id_varout(9), zdum_a , 1, npiglo, npjglo, ktime=jt)
+
+              !zdum=zint  (:,:,1) - zint  (:,:,2) ; WHERE ((tmask == 0.)  .OR. (zdum < 0 ) ) zdum = zspval
+           zdum=zint  (:,:,2) - zint  (:,:,1) ; WHERE (tmask == 0.) zdum = zspval
+           !ierr = putvar(ncout, id_varout(2), zdum, jiso-1, npiglo, npjglo, ktime=jt) !Saves thickness
+           ierr = putvar(ncout, id_varout(2), zdum, 1, npiglo, npjglo, ktime=jt)
+
+              WHERE ( zdum /= zspval .AND. zdum /= 0.) 
+                 zdum_u=(du2dint(:,:,2) - du2dint(:,:,1))/ zdum
+                 zdum_v=(dv2dint(:,:,2) - dv2dint(:,:,1))/ zdum
+                 zdum_m = zdum_m / zdum
+              !ELSEWHERE
+                 !zdum_u=zspval
+                 !zdum_v=zspval
+                 !zdum_m=zspval
+              ENDWHERE
+              !ierr = putvar(ncout, id_varout(4), zdum, jiso-1, npiglo, npjglo, ktime=jt) !Saves average
+              ierr = putvar(ncout, id_varout(6), zdum_u, 1, npiglo, npjglo, ktime=jt)
+              ierr = putvar(ncout, id_varout(4), zdum_v, 1, npiglo, npjglo, ktime=jt)
+              ierr = putvar(ncout, id_varout(8), zdum_m, 1, npiglo, npjglo, ktime=jt)
+
+           !ENDIF
+           !dv2dint(:,:,2) = dv2dint(:,:,1)
+           !zint   (:,:,2) = zint   (:,:,1)
+
+        END DO
+     !END DO
+     ierr = closeout(ncout)
+  !END DO  ! loop on scalar files
+  PRINT *,' integral between isopycnals completed successfully'
+END  PROGRAM cdfsigintegr_pedro
diff --git a/cdfsig0.f90 b/src/cdfsigntr.f90
similarity index 77%
rename from cdfsig0.f90
rename to src/cdfsigntr.f90
index 2b67c38..e72eb66 100644
--- a/cdfsig0.f90
+++ b/src/cdfsigntr.f90
@@ -1,14 +1,13 @@
-PROGRAM cdfsig0
+PROGRAM cdfsigntr
   !!======================================================================
-  !!                     ***  PROGRAM  cdfsig0  ***
+  !!                     ***  PROGRAM  cdfsigntr  ***
   !!=====================================================================
-  !!  ** Purpose : Compute sigma0 3D field from gridT file
+  !!  ** Purpose : Compute ntr volumic mass 3D field from gridT file
   !!               Store the results on a 'similar' cdf file.
   !!
-  !!  ** Method  : Use NEMO equation of state
+  !!  ** Method  : Use Mc Dougall Jackett EOS (2005)
   !!
-  !! History : 2.1  : 11/2006  : J.M. Molines : Original code
-  !!           3.0  : 01/2011  : J.M. Molines : Doctor norm + Lic.
+  !! History : 3.0  : 06/2013  : J.M. Molines from G. Madec idl code
   !!----------------------------------------------------------------------
   USE cdfio
   USE eos
@@ -31,12 +30,12 @@ PROGRAM cdfsig0
 
   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: ztemp              ! temperature
   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zsal               ! salinity
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zsig0              ! sigma-0
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zsigntr            ! sigma-0
   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zmask              ! 2D mask at current level
   REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim                ! time counter
 
   CHARACTER(LEN=256)                        :: cf_tfil            ! input filename
-  CHARACTER(LEN=256)                        :: cf_out='sig0.nc'   ! output file name
+  CHARACTER(LEN=256)                        :: cf_out='signtr.nc'   ! output file name
 
   TYPE (variable), DIMENSION(1)             :: stypvar            ! structure for attributes
   !!----------------------------------------------------------------------
@@ -44,10 +43,10 @@ PROGRAM cdfsig0
 
   narg = iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfsig0 T-file'
+     PRINT *,' usage : cdfsigntr T-file'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
-     PRINT *,'       Compute potential density (sigma-0) refered to the surface.' 
+     PRINT *,'       Compute neutral volumic mass (kg/m3) from temperature and salinity.'
      PRINT *,'      '
      PRINT *,'     ARGUMENTS :'
      PRINT *,'       T-file  : netcdf file with temperature and salinity.' 
@@ -57,10 +56,10 @@ PROGRAM cdfsig0
      PRINT *,'      '
      PRINT *,'     OUTPUT : '
      PRINT *,'       netcdf file : ', TRIM(cf_out) 
-     PRINT *,'         variables : ', TRIM(cn_vosigma0), ' ( kg/m3 - 1000 )'
+     PRINT *,'         variables : ', TRIM(cn_vosigntr), ' ( kg/m3 )'
      PRINT *,'      '
      PRINT *,'     SEE ALSO :'
-     PRINT *,'       cdfsigi'
+     PRINT *,'       cdfsig0, cdfsigi, cdfsiginsitu'
      STOP
   ENDIF
 
@@ -73,13 +72,13 @@ PROGRAM cdfsig0
   npt    = getdim (cf_tfil, cn_t)
 
   ipk(:)                       = npk  ! all variables (input and output are 3D)
-  stypvar(1)%cname             = cn_vosigma0
+  stypvar(1)%cname             = cn_vosigntr
   stypvar(1)%cunits            = 'kg/m3'
   stypvar(1)%rmissing_value    = 0.
   stypvar(1)%valid_min         = 0.001
-  stypvar(1)%valid_max         = 40.
-  stypvar(1)%clong_name        = 'Potential_density:sigma-0'
-  stypvar(1)%cshort_name       = cn_vosigma0
+  stypvar(1)%valid_max         = 1040.
+  stypvar(1)%clong_name        = 'Neutral volumic mass'
+  stypvar(1)%cshort_name       = cn_vosigntr
   stypvar(1)%conline_operation = 'N/A'
   stypvar(1)%caxis             = 'TZYX'
 
@@ -89,7 +88,7 @@ PROGRAM cdfsig0
   PRINT *, 'npt    = ', npt
 
   ALLOCATE (ztemp(npiglo,npjglo), zsal (npiglo,npjglo) )
-  ALLOCATE (zsig0(npiglo,npjglo), zmask(npiglo,npjglo) )
+  ALLOCATE (zsigntr(npiglo,npjglo), zmask(npiglo,npjglo) )
   ALLOCATE (tim(npt) )
 
   ! create output fileset
@@ -103,6 +102,7 @@ PROGRAM cdfsig0
   DO jt=1,npt
      PRINT *,' TIME = ', jt, tim(jt)/86400.,' days'
      DO jk = 1, npk
+        PRINT *, 'level : ', jk
         zmask(:,:)=1.
 
         ztemp(:,:)= getvar(cf_tfil, cn_votemper, jk, npiglo, npjglo, ktime=jt)
@@ -111,13 +111,13 @@ PROGRAM cdfsig0
         ! assuming spval is 0
         WHERE( zsal == 0 ) zmask = 0
 
-        zsig0(:,:) = sigma0 (ztemp, zsal, npiglo, npjglo )* zmask(:,:)
+        zsigntr(:,:) = sigmantr (ztemp, zsal, npiglo, npjglo )* zmask(:,:)
 
-        ierr = putvar(ncout, id_varout(1), zsig0, jk, npiglo, npjglo, ktime=jt)
+        ierr = putvar(ncout, id_varout(1), zsigntr, jk, npiglo, npjglo, ktime=jt)
 
      END DO  ! loop to next level
   END DO  ! next time frame
 
   ierr = closeout(ncout)
 
-END PROGRAM cdfsig0
+END PROGRAM cdfsigntr
diff --git a/cdfsigtrp.f90 b/src/cdfsigtrp.f90
similarity index 87%
copy from cdfsigtrp.f90
copy to src/cdfsigtrp.f90
index e298afa..a22fe8d 100644
--- a/cdfsigtrp.f90
+++ b/src/cdfsigtrp.f90
@@ -74,11 +74,11 @@ PROGRAM cdfsigtrp
    REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: eu                   ! either e1v or e2u
    REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: e3t1d, e3w1d         ! vertical metrics in case of full step
    REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: rlonlat              ! longitudes/latitudes if the section
-   REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: zs, zt               ! salinity and temperature from file 
+   REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: zs, zt, zz           ! salinity and temperature from file 
    REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: rdumlon, rdumlat     ! dummy longitude and latitude for output
    REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: zu                   ! velocity
    REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: zmask                ! mask
-   REAL(KIND=4), DIMENSION(:,:,:),   ALLOCATABLE :: tmpm, tmpz           ! temporary arrays
+   REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: tmpm, tmpz           ! temporary arrays
 
    ! double precision for cumulative variables and densities
    REAL(KIND=8)                                  :: dsigma_min           ! minimum density for bining
@@ -118,11 +118,12 @@ PROGRAM cdfsigtrp
    CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: clongname            ! output long name (root)
 
    LOGICAL                                       :: l_merid              ! flag for meridional section
-   LOGICAL                                       :: ltemp  =.FALSE.      ! flag for extra print
+   LOGICAL                                       :: ltemp  =.FALSE.      ! flag for use of temperature
    LOGICAL                                       :: lprint =.FALSE.      ! flag for extra print
    LOGICAL                                       :: lbimg  =.FALSE.      ! flag for bimg output
-   LOGICAL                                       :: lncdf  =.FALSE.      ! flag for bimg output
-   LOGICAL                                       :: lfull  =.FALSE.      ! flag for bimg output
+   LOGICAL                                       :: lncdf  =.FALSE.      ! flag for extra netcdf output
+   LOGICAL                                       :: lfull  =.FALSE.      ! flag for full step 
+   LOGICAL                                       :: lneutral  =.FALSE.   ! flag for neutral density
    LOGICAL                                       :: lchk   =.FALSE.      ! flag for missing files
    !!----------------------------------------------------------------------
    CALL ReadCdfNames()
@@ -131,7 +132,7 @@ PROGRAM cdfsigtrp
    IF ( narg < 6 ) THEN
       PRINT *,' usage :  cdfsigtrp T-file U-file V-file sigma_min sigma_max nbins ...'
       PRINT *,'              ... [-print ] [-bimg ] [-full ] [ -refdep ref_depth] ...'
-      PRINT *,'              ... [-section file ] [-temp ]'
+      PRINT *,'              ... [-neutral ] [-section file ] [-temp ]'
       PRINT *,'      '
       PRINT *,'     PURPOSE :'
       PRINT *,'       Compute density class transports, according to the density class' 
@@ -145,7 +146,7 @@ PROGRAM cdfsigtrp
       PRINT *,'       the section name.'
       PRINT *,'      '
       PRINT *,'       This program can also be used to compute transport by class of '
-      PRINT *,'       temperatures, provided the temperatures decreases monotonically '
+      PRINT *,'       temperatures, provided the temperatures decrease monotonically '
       PRINT *,'       downward. In this case, use -temp option and of course specify'
       PRINT *,'       sigma_min, sigma_max as temperatures.'
       PRINT *,'      '
@@ -171,6 +172,7 @@ PROGRAM cdfsigtrp
       PRINT *,'       [ -refdep ref_depth ]: give a reference depths for the computation of'
       PRINT *,'               potential density. Sigma_min, sigma_max must be adapted '
       PRINT *,'               accordingly.'
+      PRINT *,'       [ -neutral ]: use neutral density instead of potential density '
       PRINT *,'       [ -section file] : give the name of section file.'
       PRINT *,'               Default is ', TRIM(cf_section)
       PRINT *,'       [ -temp ] : use temperature instead of density for binning'
@@ -211,6 +213,7 @@ PROGRAM cdfsigtrp
       CASE ( '-temp')  ; ltemp  = .TRUE. 
       CASE ( '-refdep' ) ; CALL getarg(ijarg, cldum      ) ; ijarg=ijarg+1 ; READ(cldum,*) refdep
       CASE ( '-section') ; CALL getarg(ijarg, cf_section ) ; ijarg=ijarg+1 
+      CASE ( '-neutral') ; lneutral = .TRUE.
       CASE DEFAULT
          ireq=ireq+1
          SELECT CASE ( ireq)
@@ -307,125 +310,131 @@ PROGRAM cdfsigtrp
          CYCLE
       ENDIF
 
-      ALLOCATE ( zu(npts,npk), zt(npts,npk), zs(npts,npk), dsig(npts,0:npk)  )
+      ALLOCATE ( zu(npts,npk), zt(npts,npk), zs(npts,npk), zz(npts,npk), dsig(npts,0:npk)  )
       ALLOCATE ( eu(npts), de3(npts,npk), ddepu(npts, 0:npk), zmask(npts,npk) )
-      ALLOCATE ( tmpm(1,npts,2), tmpz(npts,1,2)                              )
+      ALLOCATE ( tmpm(1,npts), tmpz(npts,1)                                   )
       ALLOCATE ( dwtrp(npts, nbins+1), dhiso(npts,nbins+1), dwtrpbin(npts,nbins) )
       ALLOCATE ( rlonlat(npts,1) )
 
-      zt = 0. ; zs = 0. ; zu = 0. ; ddepu= 0. ; zmask = 0.  ; dsig=0.d0
-
-      IF (l_merid ) THEN   ! meridional section at i=iimin=iimax
-         tmpm(:,:,1)   = getvar(cn_fhgr, cn_ve2u,   1, 1, npts, kimin=iimin, kjmin=ijmin+1)
-         eu(:)         = tmpm(1,:,1)  ! metrics varies only horizontally
-         tmpm(:,:,1)   = getvar(cn_fhgr, cn_vlat2d, 1, 1, npts, kimin=iimin, kjmin=ijmin+1)
-         rlonlat(:,1)  = tmpm(1,:,1)  ! latitude in this case
-         DO jk = 1,npk
-            ! initiliaze ddepu to gdept()
-            ddepu(:,jk) = gdept(jk)
-
-            IF ( lfull ) THEN
-               de3(:,jk)   = e3t1d(jk)
-               tmpm(1,:,1) = e3w1d(jk)
-               tmpm(1,:,2) = e3w1d(jk)
-            ELSE
-               ! vertical metrics (PS case)
-               tmpm(:,:,1) = getvar(cn_fzgr, 'e3u_ps', jk, 1, npts, kimin=iimin,   kjmin=ijmin+1, ldiom=.TRUE.)
-               de3(:,jk)   = tmpm(1,:,1)
-               tmpm(:,:,1) = getvar(cn_fzgr, 'e3w_ps', jk, 1, npts, kimin=iimin,   kjmin=ijmin+1, ldiom=.TRUE.)
-               tmpm(:,:,2) = getvar(cn_fzgr, 'e3w_ps', jk, 1, npts, kimin=iimin+1, kjmin=ijmin+1, ldiom=.TRUE.)
-            ENDIF
-
-            IF (jk >= 2 ) THEN
-               DO ji=1,npts
-                  ddepu(ji,jk)= ddepu(ji,jk-1) + MIN(tmpm(1,ji,1), tmpm(1,ji,2))
-               END DO
-            ENDIF
-
-            ! Normal velocity
-            tmpm(:,:,1) = getvar(cf_ufil,cn_vozocrtx,jk,1,npts, kimin=iimin, kjmin=ijmin+1)
-            zu(:,jk)    = tmpm(1,:,1)
-
-            ! salinity and deduce umask for the section
-            tmpm(:,:,1) = getvar(cf_tfil,cn_vosaline,jk,1,npts, kimin=iimin  , kjmin=ijmin+1)
-            tmpm(:,:,2) = getvar(cf_tfil,cn_vosaline,jk,1,npts, kimin=iimin+1, kjmin=ijmin+1)
-            zmask(:,jk) = tmpm(1,:,1)*tmpm(1,:,2)
-            WHERE ( zmask(:,jk) /= 0 ) zmask(:,jk)=1
-            ! do not take special care for land value, as the corresponding velocity point is masked
-            zs(:,jk) = 0.5 * ( tmpm(1,:,1) + tmpm(1,:,2) )
-
-            ! limitation to 'wet' points
-            IF ( SUM(zs(:,jk))  == 0 ) THEN
-               nk=jk ! first vertical point of the section full on land
-               EXIT  ! as soon as all the points are on land
+      zt = 0. ; zs = 0. ; zu = 0. ; ddepu= 0.d0 ; zmask = 0.  ; dsig=0.d0
+
+      IF (l_merid ) THEN   ! meridional section at i=iimin=iimax  ! use getvaryz
+         tmpm(:,:)    = getvar(cn_fhgr, cn_ve2u,   1, 1, npts, kimin=iimin, kjmin=ijmin+1)
+         eu(:)        = tmpm(1,:)  ! metrics varies only horizontally
+         tmpm(:,:)    = getvar(cn_fhgr, cn_vlat2d, 1, 1, npts, kimin=iimin, kjmin=ijmin+1)
+         rlonlat(:,1) = tmpm(1,:)  ! latitude in this case
+
+         ! use zt and zs as temporaty variable for e3w
+         IF ( lfull ) THEN
+           DO ji=1, npts
+             de3(ji,:) = e3t1d(:)
+             zt( ji,:) = e3w1d(:)
+             zs( ji,:) = e3w1d(:)
+           ENDDO
+         ELSE
+           de3(:,:) = getvaryz(cn_fzgr,'e3u', iimin,   npts, npk, kjmin=ijmin+1 )
+           zt( :,:) = getvaryz(cn_fzgr,'e3w', iimin,   npts, npk, kjmin=ijmin+1 )
+           zs( :,:) = getvaryz(cn_fzgr,'e3w', iimin+1, npts, npk, kjmin=ijmin+1 )
+         ENDIF
+         
+         DO ji=1, npts
+            ddepu(ji,1:npk) = gdept(:)
+         ENDDO
+
+         DO jk=2, npk
+            DO ji=1,npts
+               ddepu(ji,jk) = ddepu(ji,jk-1) +MIN (zt(ji,jk), zs(ji,jk) )
+            ENDDO
+         ENDDO
+         ! normal velocity
+         zu( :,:) = getvaryz(cf_ufil, cn_vozocrtx, iimin,   npts, npk, kjmin=ijmin+1 )
+
+         ! salinity and deduce umask for the section
+         zs( :,:) = getvaryz(cf_tfil, cn_vosaline, iimin,   npts, npk, kjmin=ijmin+1 )
+         zt( :,:) = getvaryz(cf_tfil, cn_vosaline, iimin+1, npts, npk, kjmin=ijmin+1 )
+         zmask(:,:) = zs(:,:) * zt(:,:)
+         WHERE ( zmask(:,:) /= 0 ) zmask(:,:)=1
+         zs (:,:) = 0.5 * ( zs(:,:) + zt(:,:) )
+
+         ! limitation to 'wet' points
+         DO jk = 1, npk
+            IF ( SUM(zs(:,jk)) == 0 ) THEN
+               nk=jk
+               EXIT
             ENDIF
-
-            ! temperature
-            tmpm(:,:,1) = getvar(cf_tfil, cn_votemper, jk, 1, npts, kimin=iimin,   kjmin=ijmin+1)
-            tmpm(:,:,2) = getvar(cf_tfil, cn_votemper, jk, 1, npts, kimin=iimin+1, kjmin=ijmin+1)
-            zt(:,jk) = 0.5 * ( tmpm(1,:,1) + tmpm(1,:,2) )
-         END DO
+         ENDDO
+        
+         ! temperature
+         zt(:,:) = getvaryz(cf_tfil, cn_votemper, iimin  , npts, npk, kjmin=ijmin+1 )
+         zz(:,:) = getvaryz(cf_tfil, cn_votemper, iimin+1, npts, npk, kjmin=ijmin+1 )
+         zt(:,:) = 0.5 * ( zt(:,:) + zz(:,:) )
+ 
 
       ELSE                   ! zonal section at j=ijmin=ijmax
-         tmpz(:,:,1)  = getvar(cn_fhgr, cn_ve1v,   1, npts, 1, kimin=iimin, kjmin=ijmin)
-         eu(:)        = tmpz(:,1,1)
-         tmpz(:,:,1)  = getvar(cn_fhgr, cn_vlon2d, 1, npts, 1, kimin=iimin, kjmin=ijmin)
-         rlonlat(:,1) = tmpz(:,1,1)  ! longitude in this case
-         DO jk=1,npk
-            ! initiliaze ddepu to gdept()
-            ddepu(:,jk) = gdept(jk)
-
-            IF ( lfull ) THEN
-               de3(:,jk)   = e3t1d(jk)
-               tmpm(:,1,1) = e3w1d(jk)
-               tmpm(:,1,2) = e3w1d(jk)
-            ELSE
-               ! vertical metrics (PS case)
-               tmpz(:,:,1)=getvar(cn_fzgr,'e3v_ps',jk, npts, 1, kimin=iimin+1, kjmin=ijmin, ldiom=.TRUE.)
-               de3(:,jk) = tmpz(:,1,1)
-               tmpz(:,:,1)=getvar(cn_fzgr,'e3w_ps',jk,npts,1, kimin=iimin+1, kjmin=ijmin,   ldiom=.TRUE.)
-               tmpz(:,:,2)=getvar(cn_fzgr,'e3w_ps',jk,npts,1, kimin=iimin+1, kjmin=ijmin+1, ldiom=.TRUE.)
-            ENDIF
-
-            IF (jk >= 2 ) THEN
-               DO ji=1,npts
-                  ddepu(ji,jk)= ddepu(ji,jk-1) + MIN(tmpz(ji,1,1), tmpz(ji,1,2))
-               END DO
-            ENDIF
-
-            ! Normal velocity
-            tmpz(:,:,1)=getvar(cf_vfil,cn_vomecrty,jk,npts,1, kimin=iimin+1, kjmin=ijmin)
-            zu(:,jk)=tmpz(:,1,1)
-
-            ! salinity and mask
-            tmpz(:,:,1)=getvar(cf_tfil,cn_vosaline,jk, npts, 1, kimin=iimin+1, kjmin=ijmin)
-            tmpz(:,:,2)=getvar(cf_tfil,cn_vosaline,jk, npts, 1, kimin=iimin+1, kjmin=ijmin+1)
-            zmask(:,jk)=tmpz(:,1,1)*tmpz(:,1,2)
-            WHERE ( zmask(:,jk) /= 0 ) zmask(:,jk)=1
-            ! do not take special care for land value, as the corresponding velocity point is masked
-            zs(:,jk) = 0.5 * ( tmpz(:,1,1) + tmpz(:,1,2) )
-
-            ! limitation to 'wet' points
-            IF ( SUM(zs(:,jk))  == 0 ) THEN
-               nk=jk ! first vertical point of the section full on land
-               EXIT  ! as soon as all the points are on land
+         tmpz(:,:)    = getvar(cn_fhgr, cn_ve1v,   1, npts, 1, kimin=iimin, kjmin=ijmin)
+         eu(:)        = tmpz(:,1)
+         tmpz(:,:)    = getvar(cn_fhgr, cn_vlon2d, 1, npts, 1, kimin=iimin, kjmin=ijmin)
+         rlonlat(:,1) = tmpz(:,1)  ! longitude in this case
+
+         ! use zt and zs as temporaty variable for e3w
+         IF ( lfull ) THEN
+           DO ji=1, npts
+             de3(ji,:) = e3t1d(:)
+             zt( ji,:) = e3w1d(:)
+             zs( ji,:) = e3w1d(:)
+           ENDDO
+         ELSE
+           de3(:,:) = getvarxz(cn_fzgr,'e3v', ijmin,   npts, npk, kimin=iimin+1 )
+           zt( :,:) = getvarxz(cn_fzgr,'e3w', ijmin,   npts, npk, kimin=iimin+1 )
+           zs( :,:) = getvarxz(cn_fzgr,'e3w', ijmin+1, npts, npk, kimin=iimin+1 )
+         ENDIF
+         
+         DO ji=1, npts
+            ddepu(ji,1:npk) = gdept(:)
+         ENDDO
+
+         DO jk=2, npk
+            DO ji=1,npts
+               ddepu(ji,jk) = ddepu(ji,jk-1) +MIN (zt(ji,jk), zs(ji,jk) )
+            ENDDO
+         ENDDO
+
+         ! normal velocity
+         zu( :,:) = getvarxz(cf_vfil, cn_vomecrty, ijmin,   npts, npk, kimin=iimin+1 )
+
+         ! salinity and deduce umask for the section
+         zs( :,:) = getvarxz(cf_tfil, cn_vosaline, ijmin,   npts, npk, kimin=iimin+1 )
+         zt( :,:) = getvarxz(cf_tfil, cn_vosaline, ijmin+1, npts, npk, kimin=iimin+1 )
+         zmask(:,:) = zs(:,:) * zt(:,:)
+         WHERE ( zmask(:,:) /= 0 ) zmask(:,:)=1
+         zs (:,:) = 0.5 * ( zs(:,:) + zt(:,:) )
+
+         ! limitation to 'wet' points
+         DO jk = 1, npk
+            IF ( SUM(zs(:,jk)) == 0 ) THEN
+               nk=jk
+               EXIT
             ENDIF
-
-            ! temperature
-            tmpz(:,:,1)=getvar(cf_tfil,cn_votemper,jk, npts, 1, kimin=iimin+1, kjmin=ijmin)
-            tmpz(:,:,2)=getvar(cf_tfil,cn_votemper,jk, npts, 1, kimin=iimin+1, kjmin=ijmin+1)
-            zt(:,jk) = 0.5 * ( tmpz(:,1,1) + tmpz(:,1,2) )
-         END DO
+         ENDDO
+        
+         ! temperature
+         zt(:,:) = getvarxz(cf_tfil, cn_votemper, ijmin  , npts, npk, kimin=iimin+1 )
+         zz(:,:) = getvarxz(cf_tfil, cn_votemper, ijmin+1, npts, npk, kimin=iimin+1 )
+         zt(:,:) = 0.5 * ( zt(:,:) + zz(:,:) )
 
       ENDIF
 
       ! compute density only for wet points
-      IF ( refdep == -10. ) THEN
-         dsig(:,1:nk)= -zt(:,:)  ! change sign 
-      ELSEIF ( refdep == 0. ) THEN
-         dsig(:,1:nk)=sigma0( zt, zs,         npts, nk)*zmask(:,:)
+      IF ( lneutral ) THEN 
+         dsig(:,1:nk)=sigmantr( zt, zs,         npts, nk)*zmask(:,:)
       ELSE
-         dsig(:,1:nk)=sigmai( zt, zs, refdep, npts, nk)*zmask(:,:)
+        IF ( refdep == -10. ) THEN
+           dsig(:,1:nk)= -zt(:,:)  ! change sign 
+        ELSEIF ( refdep == 0. ) THEN
+           dsig(:,1:nk)=sigma0( zt, zs,         npts, nk)*zmask(:,:)
+        ELSE
+           dsig(:,1:nk)=sigmai( zt, zs, refdep, npts, nk)*zmask(:,:)
+        ENDIF
       ENDIF
 
       dsig(:,0)=dsig(:,1)-1.e-4   ! dummy layer for easy interpolation
@@ -484,7 +493,7 @@ PROGRAM cdfsigtrp
       PRINT *,' Total transport in all bins :',TRIM(csection(jsec)),' ',SUM(dtrpbin(jsec,:) )/1.d6
 
       ! free memory for the next section
-      DEALLOCATE ( zu, zt, zs, dsig, ddepu, dhiso, dwtrp, dwtrpbin )
+      DEALLOCATE ( zu, zt, zs, zz, dsig, ddepu, dhiso, dwtrp, dwtrpbin )
       DEALLOCATE ( eu, de3, tmpm, tmpz, zmask, rlonlat             )
 
    END DO   ! next section
diff --git a/src/cdfsigtrp_broken.f90 b/src/cdfsigtrp_broken.f90
new file mode 100644
index 0000000..979adba
--- /dev/null
+++ b/src/cdfsigtrp_broken.f90
@@ -0,0 +1,883 @@
+PROGRAM cdfsigtrp_broken
+  !!======================================================================
+  !!                     ***  PROGRAM  cdfsigtrp_broken  ***
+  !!======================================================================
+  !!  ** Purpose : Compute density class Mass transport across a section.
+  !!               prviously extracted with cdf_xtrac_broken_line
+  !!           
+  !!  ** Method  :- The begining and end point of the section are given in 
+  !!                term of f-points index.
+  !!              - The program works for zonal or meridional sections.
+  !!              - The section definitions are given in an ASCII FILE 
+  !!                dens_section.dat:
+  !!                 foreach sections, 2 lines :
+  !!                       (i) : section name (String, no blank)
+  !!                      (ii) : imin imax jmin jmax for the section
+  !!              - Only vertical slices corrsponding to the sections are
+  !!                read in the files.
+  !!              - read metrics, depth, etc
+  !!              - read normal velocity (either vozocrtx oy vomecrty )
+  !!              - read 2 rows of T and S ( i i+1  or j j+1 )
+  !!              - compute the mean value at velocity point
+  !!              - compute sigma0 (can be easily modified for sigmai )
+  !!              - compute the depths of isopyncal surfaces
+  !!              - compute the transport from surface to the isopycn
+  !!              - compute the transport in each class of density
+  !!              - compute the total transport (for information)
+  !!
+  !! History : 3.0  : 12/2014  : P. Colombo   : from cdfsigtrp 
+  !!----------------------------------------------------------------------
+  !!----------------------------------------------------------------------
+  !!   routines      : description
+  !!  section_init   : initialize section names and positions
+  !!  print_out      : routine which performs standard output if required
+  !!  bimg_writ      : routine which performs bimg output if required
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE eos          ! for sigma0, sigmai
+  USE modcdfnames  ! for ReadCdfNames
+  USE modutils     ! for SetGlobalAtt
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id: cdfsigtrp.f90 699 2013-06-24 14:17:21Z molines $
+  !! Copyright (c) 2011, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)                               :: ji, jk, jclass, jsec ! dummy loop index
+  INTEGER(KIND=4)                               :: jiso, jbin, jarg     ! dummy loop index
+  INTEGER(KIND=4)                               :: nbins                ! number of density classes
+  INTEGER(KIND=4)                               :: ipos                 ! working variable
+  INTEGER(KIND=4)                               :: narg, iargc          ! command line 
+  INTEGER(KIND=4)                               :: ijarg, ireq          ! command line
+  INTEGER(KIND=4)                               :: npk, nk              ! vertical size, number of wet layers
+  INTEGER(KIND=4)                               :: numbimg=10           ! optional bimg logical unit
+  INTEGER(KIND=4)                               :: numout=11            ! ascii output
+  INTEGER(KIND=4)                               :: nsection             ! number of sections (overall)
+  INTEGER(KIND=4)                               :: iimin, iimax         ! working section limits
+  INTEGER(KIND=4)                               :: ijmin, ijmax         ! working section limits
+  INTEGER(KIND=4)                               :: npts                 ! number of points in section
+  INTEGER(KIND=4)                               :: ikx=1, iky=1         ! dims of netcdf output file
+  INTEGER(KIND=4)                               :: nboutput=2           ! number of values to write in cdf output
+  INTEGER(KIND=4)                               :: ncout, ierr          ! for netcdf output
+  INTEGER(KIND=4)                               :: iweight              ! weight of input file for further averaging
+  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: iimina, iimaxa       ! sections limits
+  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: ijmina, ijmaxa       ! sections limits
+  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: ipk, id_varout       ! variable levels and id
+
+  REAL(KIND=4)                                  :: refdep =0.e0         ! reference depth (m)
+  REAL(KIND=4), DIMENSION(1)                    :: tim                  ! time counter
+  REAL(KIND=4), DIMENSION(1)                    :: rdummy1, rdummy2     ! working variable
+  REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: gdept, gdepw         ! depth of T and W points 
+  REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: eu                   ! either e1v or e2u
+  REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: e3t1d, e3w1d         ! vertical metrics in case of full step
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: rlonlat              ! longitudes/latitudes if the section
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: zs, zt               ! salinity and temperature from file 
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: rdumlon, rdumlat     ! dummy longitude and latitude for output
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: zu                   ! velocity
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: zmask                ! mask
+  REAL(KIND=4), DIMENSION(:,:,:),   ALLOCATABLE :: tmpm, tmpz           ! temporary arrays
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: tmpz1d               ! temporary arrays
+  ! double precision for cumulative variables and densities
+  REAL(KIND=8)                                  :: dsigma_min           ! minimum density for bining
+  REAL(KIND=8)                                  :: dsigma_max, dltsig   ! maximum density for bining, step
+  REAL(KIND=8)                                  :: dsigma, dalfa        ! working sigma, interpolation coeff.
+  REAL(KIND=8), DIMENSION(:),       ALLOCATABLE :: dsigma_lev           ! built array with sigma levels
+  REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: de3                  ! vertical metrics
+  REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: ddepu                ! depth of vel points
+  REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: dsig                 ! density
+  REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: dhiso                ! depth of isopycns
+  REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: dwtrp, dwtrpbin      ! transport arrays
+  REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: dtrpbin              ! transport arrays
+
+  TYPE(variable), DIMENSION(:),     ALLOCATABLE :: stypvar              ! structure of output
+
+  CHARACTER(LEN=256)                            :: cf_brfi              ! temperature salinity velocity file 
+  !(from cdf_xtrac_brokenline)
+  CHARACTER(LEN=256)                            :: cf_section='dens_section.dat'  ! input section file
+  CHARACTER(LEN=256)                            :: cf_out='trpsig.txt'  ! output  ascii file
+  CHARACTER(LEN=256)                            :: cf_bimg              ! output bimg file (2d)
+  CHARACTER(LEN=256)                            :: cf_nc                ! output netcdf file (2d)
+  CHARACTER(LEN=256)                            :: cf_outnc             ! output netcdf file (1d, 0d))
+  CHARACTER(LEN=256)                            :: cv_dep               ! depth variable
+  CHARACTER(LEN=256)                            :: cldum                ! dummy string
+  CHARACTER(LEN=256)                            :: cglobal              ! global attribute
+  CHARACTER(LEN=80 )                            :: cfmt_9000            ! format string 
+  CHARACTER(LEN=80 )                            :: cfmt_9001            ! format string
+  CHARACTER(LEN=80 )                            :: cfmt_9002            ! format string
+  CHARACTER(LEN=80 )                            :: cfmt_9003            ! format string
+  CHARACTER(LEN=256)                            :: cl_vnam, cl_lname    ! working variables
+  CHARACTER(LEN=256)                            :: csuffixvarname       !
+  CHARACTER(LEN=256)                            :: cprefixlongname      !
+  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_names             ! names of input variables
+  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: csection             ! section name
+  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cvarname             ! output variable name (root)
+  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: clongname            ! output long name (root)
+
+  LOGICAL                                       :: ltemp  =.FALSE.      ! flag for use of temperature
+  LOGICAL                                       :: lprint =.FALSE.      ! flag for extra print
+  LOGICAL                                       :: lbimg  =.FALSE.      ! flag for bimg output
+  LOGICAL                                       :: lncdf  =.FALSE.      ! flag for extra netcdf output
+  LOGICAL                                       :: lfull  =.FALSE.      ! flag for full step 
+  LOGICAL                                       :: lneutral  =.FALSE.   ! flag for neutral density
+  LOGICAL                                       :: lchk   =.FALSE.      ! flag for missing files
+  !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  narg= iargc()
+  IF ( narg < 4 ) THEN
+     PRINT *,' usage :  cdfsigtrp_broken TSV-file sigma_min sigma_max nbins ...'
+     PRINT *,'              ... [-print ] [-bimg ] [-full ] [ -refdep ref_depth] ...'
+     PRINT *,'              ... [-neutral ] [-section file ] [-temp ]'
+     PRINT *,'      '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'       Compute density class transports, according to the density class' 
+     PRINT *,'       definition ( minimum, maximum and number of bins) given in arguments.'
+     PRINT *,'       Section position are given in ',TRIM(cf_section),', an ASCII file '
+     PRINT *,'       with pairs of lines giving section name and section location as'
+     PRINT *,'       imin imax jmin jmax. Only zonal or meridional section are allowed.'
+     PRINT *,'       The name of this file can be specified with the -section option, if'
+     PRINT *,'       it differs from the standard name. Optionaly, a netcdf root variable '
+     PRINT *,'       name and a netcdf root long-name can be provided on the line giving '
+     PRINT *,'       the section name.'
+     PRINT *,'       In this particular tool, the section used is the result of '
+     PRINT *,'       cdf_xtrac_brokenline. In this way, it is possible to calculate the'
+     PRINT *,'       transport of density class in oblicous sections (non dependance on '
+     PRINT *,'       zonal or meridional).'
+     PRINT *,'      '
+     PRINT *,'       This program can also be used to compute transport by class of '
+     PRINT *,'       temperatures, provided the temperatures decrease monotonically '
+     PRINT *,'       downward. In this case, use -temp option and of course specify'
+     PRINT *,'       sigma_min, sigma_max as temperatures.'
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       TSV-file : netcdf_broken_line file with temperature, salinity' 
+     PRINT *,'       and the normal velocity through the section'
+     PRINT *,'       sigma_min : minimum density for binning'
+     PRINT *,'       sigma_max : maximum density for binning'
+     PRINT *,'       nbins : number of bins. This will fix the bin ''width'' '
+     PRINT *,'      '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'       [ -full ] : for full step configuration' 
+     PRINT *,'       [ -bimg ] : produce extra bimg output file which shows the details'
+     PRINT *,'               of the sections (normal velocity, density, temperature, '
+     PRINT *,'               salinity, transports, isopycnal depths. (to be change to '
+     PRINT *,'               netcdf files for more common use.'
+     PRINT *,'       [ -ncdf ] : produce extra netcdf output file which shows the details'
+     PRINT *,'               of the sections (normal velocity, density, temperature, '
+     PRINT *,'               salinity, transports, isopycnal depths. '
+     PRINT *,'       [ -print ]: write the binned transports on standard output, for each'
+     PRINT *,'               sections.'
+     PRINT *,'       [ -refdep ref_depth ]: give a reference depths for the computation of'
+     PRINT *,'               potential density. Sigma_min, sigma_max must be adapted '
+     PRINT *,'               accordingly.'
+     PRINT *,'       [ -neutral ]: use neutral density instead of potential density '
+     PRINT *,'       [ -section file] : give the name of section file.'
+     PRINT *,'               Default is ', TRIM(cf_section)
+     PRINT *,'       [ -temp ] : use temperature instead of density for binning'
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'       ', TRIM(cn_fzgr),' and ', TRIM(cf_section)
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       Netcdf file : There is 1 netcdf file per section. File name is build'
+     PRINT *,'         from section name : Section_name_trpsig.nc'
+     PRINT *,'         variables : sigma_class (upper limit of the bin)'
+     PRINT *,'                     sigtrp : transport (Sv per bin)'
+     PRINT *,'      '
+     PRINT *,'       ascii file  : ', TRIM(cf_out) 
+     PRINT *,'      '
+     PRINT *,'       bimg  file  :  There are 2 bimg files whose name is build from section'
+     PRINT *,'         name : section_name_trpdep.bimg and section_name_trpsig.bimg.'
+     PRINT *,'         This file is written only if -bimg option is used.'
+     PRINT *,'      '
+     PRINT *,'      Standard output : the results are written on standard output only if '
+     PRINT *,'         the -print option is used.'
+     PRINT *,'      '
+     PRINT *,'     SEE ALSO :'
+     PRINT *,'      cdfrhoproj, cdftransport, cdfsigintegr, cdfsigtrp, cdf_xtrac_brokenline '
+     PRINT *,'      '
+     STOP
+  ENDIF
+
+  ! browse command line
+  ijarg = 1 ; ireq = 0
+  DO WHILE ( ijarg <= narg )
+     CALL getarg(ijarg, cldum ) ; ijarg=ijarg+1
+     SELECT CASE ( cldum )
+     CASE ( '-full' ) ; lfull  = .TRUE.
+     CASE ( '-bimg' ) ; lbimg  = .TRUE.
+     CASE ( '-ncdf' ) ; lncdf  = .TRUE.
+     CASE ( '-print') ; lprint = .TRUE.
+     CASE ( '-temp')  ; ltemp  = .TRUE. 
+     CASE ( '-refdep' ) ; CALL getarg(ijarg, cldum      ) ; ijarg=ijarg+1 ; READ(cldum,*) refdep
+     CASE ( '-section') ; CALL getarg(ijarg, cf_section ) ; ijarg=ijarg+1 
+     CASE ( '-neutral') ; lneutral = .TRUE.
+     CASE DEFAULT
+        ireq=ireq+1
+        SELECT CASE ( ireq)
+        CASE ( 1 ) ; cf_brfi = cldum
+        CASE ( 2 ) ; READ(cldum,*) dsigma_min
+        CASE ( 3 ) ; READ(cldum,*) dsigma_max
+        CASE ( 4 ) ; READ(cldum,*) nbins
+        CASE DEFAULT 
+           PRINT *,' Too many arguments ' ; STOP
+        END SELECT
+     END SELECT
+  END DO
+  ! check for file existence
+  lchk = lchk .OR. chkfile( cn_fzgr    )
+  lchk = lchk .OR. chkfile( cf_section )
+  lchk = lchk .OR. chkfile( cf_brfi    )
+  IF ( lchk ) STOP ! missing file
+  IF ( ltemp)  THEN  ! temperature decrease downward. Change sign and swap min/max
+     refdep = -10. ! flag value
+     dltsig     = dsigma_max  ! use dltsig as dummy variable for swapping
+     dsigma_max = -dsigma_min
+     dsigma_min = -dltsig
+  ENDIF
+
+  ! define global attribute with command line
+  CALL SetGlobalAtt( cglobal)
+
+  !! Commented Pedro   
+  ! get the attribute iweight from vozocrtx
+  ! JM iweight can be taken from cf_brfi as well
+  !iweight = getatt(cf_ufil, cn_vozocrtx, 'iweight')
+  iweight = 1
+  IF ( iweight == 0 ) iweight = 1  ! if 0 means that it is not defined.
+
+  ALLOCATE ( stypvar(nboutput), ipk(nboutput), id_varout(nboutput) )
+  ALLOCATE ( rdumlon(ikx,iky),  rdumlat(ikx,iky)                   )
+
+  rdumlon(:,:)=0.
+  rdumlat(:,:)=0.
+
+  ipk(1)=nbins ! sigma for each level
+  ipk(2)=nbins ! transport for each level
+  ! initialisation of variable names etc... is done according to section name
+
+  ! Initialise sections from file 
+  ! first call to get nsection and allocate arrays 
+  nsection = 0 ; CALL section_init(cf_section, csection,cvarname,clongname,iimina, iimaxa, ijmina, ijmaxa, nsection)
+  ALLOCATE ( csection(nsection), cvarname(nsection), clongname(nsection) )
+  ALLOCATE ( iimina(nsection), iimaxa(nsection), ijmina(nsection),ijmaxa(nsection) )
+  CALL section_init(cf_section, csection,cvarname,clongname, iimina,iimaxa,ijmina,ijmaxa, nsection)
+
+  ! Allocate and build sigma levels and section array
+  ALLOCATE ( dsigma_lev (nbins+1) , dtrpbin(nsection,nbins)  )
+
+  dsigma_lev(1)=dsigma_min
+  dltsig=( dsigma_max - dsigma_min) / nbins
+  DO jclass =2, nbins+1
+     dsigma_lev(jclass)= dsigma_lev(1) + (jclass-1) * dltsig
+  END DO
+
+  ! Look for vertical size of the domain
+  npk = getdim (cf_brfi,cn_z)
+  ALLOCATE ( gdept(npk), gdepw(npk) )
+  IF ( lfull ) ALLOCATE ( e3t1d(npk), e3w1d(npk))
+
+  ! read gdept, gdepw : it is OK even in partial cells, as we never use the bottom gdep
+  gdept(:) = getvare3(cn_fzgr, cn_gdept, npk)
+  gdepw(:) = getvare3(cn_fzgr, cn_gdepw, npk)
+
+  IF ( lfull )  THEN 
+     e3t1d(:) = getvare3(cn_fzgr, cn_ve3t, npk)
+     e3w1d(:) = getvare3(cn_fzgr, cn_ve3w, npk)
+  ENDIF
+
+  !! *  Main loop on sections
+  DO jsec=1,nsection
+     iimin=iimina(jsec) ; iimax=iimaxa(jsec)
+     ijmin=ijmina(jsec) ; ijmax=ijmaxa(jsec)
+
+     IF (iimin == iimax ) THEN        ! meridional section
+        npts    = ijmax - ijmin       ! number of segments
+
+     ELSE IF ( ijmin == ijmax ) THEN  ! zonal section
+        npts    = iimax - iimin       ! number of segments
+
+     ELSE
+        PRINT *,' Section ',TRIM(csection(jsec)),' is neither zonal nor meridional :('
+        PRINT *,' We skip this section .'
+        CYCLE
+     ENDIF
+
+     ALLOCATE ( zu(npts,npk), zt(npts,npk), zs(npts,npk), dsig(npts,0:npk)  )
+     ALLOCATE ( eu(npts), de3(npts,npk), ddepu(npts, 0:npk), zmask(npts,npk) )
+     ALLOCATE ( tmpm(1,npts,2), tmpz(npts,1,2)                              )
+     ALLOCATE ( dwtrp(npts, nbins+1), dhiso(npts,nbins+1), dwtrpbin(npts,nbins) )
+     ALLOCATE ( rlonlat(npts,1) )
+
+
+     ! zonal section at j=ijmin=ijmax
+     tmpz(:,:,1)  = getvar(cf_brfi, cn_ve1v,   1, npts, 1, kimin=iimin, kjmin=ijmin)
+     eu(:)        = tmpz(:,1,1)
+     tmpz(:,:,1)  = getvar(cf_brfi, cn_vlon2d, 1, npts, 1, kimin=iimin, kjmin=ijmin)
+     rlonlat(:,1) = tmpz(:,1,1)  ! longitude in this case
+     DO jk=1,npk
+        ! initiliaze ddepu to gdept()
+        ddepu(:,jk) = gdept(jk)
+
+        IF ( lfull ) THEN
+           de3(:,jk)   = e3t1d(jk)
+           tmpm(:,1,1) = e3w1d(jk)
+           tmpm(:,1,2) = e3w1d(jk)
+        ELSE
+           ! vertical metrics (PS case)
+           tmpz(:,:,1)=getvar(cf_brfi,'e3v_ps',jk, npts, 1, kimin=iimin+1, kjmin=ijmin, ldiom=.TRUE.)
+           de3(:,jk) = tmpz(:,1,1)
+        ENDIF
+
+        IF (jk >= 2 ) THEN
+           DO ji=1,npts
+              ddepu(ji,jk)= ddepu(ji,jk-1) + tmpz(ji,1,1)!MIN(tmpz(ji,1,1), tmpz(ji,1,2))
+           END DO
+        ENDIF
+
+        ! Normal velocity
+        tmpz(:,:,1)=getvar(cf_brfi,cn_vomecrty,jk,npts,1, kimin=iimin+1, kjmin=ijmin)
+        zu(:,jk)=tmpz(:,1,1)
+        ! salinity and mask
+        tmpz(:,:,1)=getvar(cf_brfi,cn_vosaline,jk,npts,1, kimin=iimin+1, kjmin=ijmin)
+        zmask(:,jk)=tmpz(:,1,1)
+        WHERE ( zmask(:,jk) /= 0 ) zmask(:,jk)=1
+        ! do not take special care for land value, as the corresponding velocity point is masked
+        zs(:,jk) = tmpz(:,1,1)
+        ! limitation to 'wet' points
+        IF ( SUM(zs(:,jk))  == 0 ) THEN
+           nk=jk ! first vertical point of the section full on land
+           EXIT  ! as soon as all the points are on land
+        ENDIF
+
+        ! temperature
+        tmpz(:,:,1)=getvar(cf_brfi,cn_votemper,jk, npts, 1, kimin=iimin+1, kjmin=ijmin)
+        zt(:,jk) = tmpz(:,1,1)
+     END DO
+     ! compute density only for wet points
+     IF ( lneutral ) THEN 
+        dsig(:,1:nk)=sigmantr( zt, zs,         npts, npk)*zmask(:,:)
+     ELSE
+        IF ( refdep == -10. ) THEN
+           dsig(:,1:nk)= -zt(:,:)  ! change sign 
+        ELSEIF ( refdep == 0. ) THEN
+           dsig(:,1:nk)=sigma0( zt, zs,         npts, npk)*zmask(:,:)
+        ELSE
+           dsig(:,1:nk)=sigmai( zt, zs, refdep, npts, npk)*zmask(:,:)
+        ENDIF
+     ENDIF
+
+     dsig(:,0)=dsig(:,1)-1.e-4   ! dummy layer for easy interpolation
+
+     ! compute depth of isopynals (nbins+1 )
+     DO  jiso =1, nbins+1
+        dsigma=dsigma_lev(jiso)
+!!!  REM : I and K loop can be inverted if necessary
+        DO ji=1,npts
+           dhiso(ji,jiso) = gdept(npk)
+           DO jk=1,nk 
+              IF ( dsig(ji,jk) < dsigma ) THEN
+              ELSE
+                 ! interpolate between jk-1 and jk
+                 dalfa=(dsigma - dsig(ji,jk-1)) / ( dsig(ji,jk) -dsig(ji,jk-1) )
+                 IF (ABS(dalfa) > 1.1 .OR. dalfa < 0 ) THEN   ! case dsig(0) = dsig(1)-1.e-4
+                    dhiso(ji,jiso)= 0.d0
+                 ELSE
+                    dhiso(ji,jiso)= ddepu(ji,jk)*dalfa + (1.d0-dalfa)* ddepu(ji,jk-1)
+                 ENDIF
+                 EXIT
+              ENDIF
+           END DO
+        END DO
+     END DO
+
+     ! compute transport between surface and isopycn 
+     DO jiso = 1, nbins + 1
+        dsigma=dsigma_lev(jiso)
+        DO ji=1,npts
+           dwtrp(ji,jiso) = 0.d0
+           DO jk=1, nk-1
+              IF ( gdepw(jk+1) < dhiso(ji,jiso) ) THEN
+                 dwtrp(ji,jiso)= dwtrp(ji,jiso) + eu(ji)*de3(ji,jk)*zu(ji,jk)*1.d0
+              ELSE  ! last box ( fraction)
+                 dwtrp(ji,jiso)= dwtrp(ji,jiso) + eu(ji)*(dhiso(ji,jiso)-gdepw(jk))*zu(ji,jk)*1.d0
+                 EXIT  ! jk loop
+              ENDIF
+           END DO
+        END DO
+     END DO
+
+     ! binned transport : difference between 2 isopycns
+     DO jbin=1, nbins
+        dsigma=dsigma_lev(jbin)
+        DO ji=1, npts
+           dwtrpbin(ji,jbin) = dwtrp(ji,jbin+1) -  dwtrp(ji,jbin) 
+        END DO
+        dtrpbin(jsec,jbin)=SUM(dwtrpbin(:,jbin) )
+     END DO
+
+     ! output of the code for 1 section
+     IF (lprint) CALL print_out(jsec)
+     IF (lbimg ) CALL bimg_writ(jsec)
+     IF (lncdf ) CALL cdf_writ(jsec)
+     PRINT *,' Total transport in all bins :',TRIM(csection(jsec)),' ',SUM(dtrpbin(jsec,:) )/1.d6
+
+     ! free memory for the next section
+     DEALLOCATE ( zu, zt, zs, dsig, ddepu, dhiso, dwtrp, dwtrpbin )
+     DEALLOCATE ( eu, de3, tmpm, tmpz, zmask, rlonlat             )
+
+  END DO   ! next section
+
+  !! Global Output
+  OPEN( numout, FILE=cf_out)
+  ipos=INDEX(cf_brfi,'_gridT.nc')
+  WRITE(numout,9006)  TRIM(cf_brfi(1:ipos-1))
+  WRITE(numout,9005) ' sigma  ', (csection(jsec),jsec=1,nsection)
+  DO jiso=1,nbins
+     WRITE(numout,9004) dsigma_lev(jiso), (dtrpbin(jsec,jiso),jsec=1,nsection)
+  ENDDO
+  CLOSE(numout)
+
+  cv_dep='levels'
+  ! need to call section_init again in order to reset cvarname, clongname if they where modified 
+  ! previously in cdf_writ(  case lncdf=true )
+  IF (lncdf) THEN
+     CALL section_init(cf_section, csection,cvarname,clongname, iimina,iimaxa,ijmina,ijmaxa, nsection)
+  ENDIF
+
+  DO jsec=1,nsection
+     ! setup output variables (section dependant for adaptative variable name (if possible)
+     ! define new variables for output 
+     IF ( cvarname(jsec) /= 'none' ) THEN
+        csuffixvarname='_'//TRIM(cvarname(jsec))
+     ELSE
+        csuffixvarname=''
+     ENDIF
+     IF ( clongname(jsec) /= 'none' ) THEN
+        cprefixlongname=TRIM(clongname(jsec))//'_'
+     ELSE
+        cprefixlongname=''
+     ENDIF
+
+     stypvar%rmissing_value    = 99999.
+     stypvar%scale_factor      = 1.
+     stypvar%add_offset        = 0.
+     stypvar%savelog10         = 0.
+     stypvar%iwght             = iweight
+     stypvar%conline_operation = 'N/A'
+     stypvar%caxis             = 'ZT'
+
+     IF ( ltemp ) THEN
+        stypvar(1)%cname          = 'temp_class'
+        stypvar(1)%cunits         = '[]'
+        stypvar(1)%valid_min      = 0.
+        stypvar(1)%valid_max      = 100.
+        stypvar(1)%clong_name     = 'class of potential temperature'
+        stypvar(1)%cshort_name    = 'temp_class'
+
+        stypvar(2)%cname          = 'temptrp'//TRIM(csuffixvarname)
+        stypvar(2)%cunits         = 'Sv'
+        stypvar(2)%valid_min      = -1000.
+        stypvar(2)%valid_max      = 1000.
+        stypvar(2)%clong_name     = TRIM(cprefixlongname)//'transport in temperature class'
+        stypvar(2)%cshort_name    = 'temptrp'
+     ELSE
+        stypvar(1)%cname          = 'sigma_class'
+        stypvar(1)%cunits         = '[]'
+        stypvar(1)%valid_min      = 0.
+        stypvar(1)%valid_max      = 100.
+        stypvar(1)%clong_name     = 'class of potential density'
+        stypvar(1)%cshort_name    = 'sigma_class'
+
+        stypvar(2)%cname          = 'sigtrp'//TRIM(csuffixvarname)
+        stypvar(2)%cunits         = 'Sv'
+        stypvar(2)%valid_min      = -1000.
+        stypvar(2)%valid_max      = 1000.
+        stypvar(2)%clong_name     = TRIM(cprefixlongname)//'transport in sigma class'
+        stypvar(2)%cshort_name    = 'sigtrp'
+     ENDIF
+
+
+     ! create output fileset
+     IF (ltemp) THEN
+        cf_outnc = TRIM(csection(jsec))//'_trptemp.nc'
+     ELSE
+        cf_outnc = TRIM(csection(jsec))//'_trpsig.nc'
+     ENDIF
+
+     ncout = create      (cf_outnc, 'none',  ikx,      iky, nbins, cdep=cv_dep               )
+     ierr  = createvar   (ncout,    stypvar, nboutput, ipk, id_varout, cdglobal=TRIM(cglobal))
+     ierr  = putheadervar(ncout,    cf_brfi, ikx,      iky, nbins, &
+          &   pnavlon=rdumlon, pnavlat=rdumlat, pdep=REAL(dsigma_lev), cdep=cv_dep           )
+
+     tim  = getvar1d(cf_brfi, cn_vtimec, 1     )
+     ierr = putvar1d(ncout,   tim,       1, 'T')
+
+     DO jiso=1,nbins
+        rdummy1 = dsigma_lev(jiso)
+        rdummy2 = dtrpbin(jsec,jiso)/1.d6  ! Sv
+        ierr    = putvar(ncout, id_varout(1), rdummy1, jiso, ikx, iky )
+        ierr    = putvar(ncout, id_varout(2), rdummy2, jiso, ikx, iky )
+     END DO
+
+     ierr = closeout(ncout)
+
+  END DO
+
+9004 FORMAT(f9.4, 20e16.7)
+9005 FORMAT('#',a9, 20(2x,a12,2x) )
+9006 FORMAT('# ',a)
+
+CONTAINS
+  SUBROUTINE section_init(cdfile, cdsection, cdvarname, cdlongname, kimin, kimax, kjmin, kjmax, knumber)
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE section_init  ***
+    !!
+    !! ** Purpose : Read input ASCII file that defines section names and limit of
+    !!              sections.
+    !!
+    !! ** Method  : At fisrt call only return the number of sections for further
+    !!              allocation.  
+    !!
+    !!----------------------------------------------------------------------
+    CHARACTER(LEN=*),                       INTENT(in   ) :: cdfile
+    CHARACTER(LEN=256), DIMENSION(knumber), INTENT(out  ) :: cdsection
+    CHARACTER(LEN=256), DIMENSION(knumber), INTENT(out  ) :: cdvarname
+    CHARACTER(LEN=256), DIMENSION(knumber), INTENT(out  ) :: cdlongname
+    INTEGER(KIND=4),                        INTENT(inout) :: knumber
+    INTEGER(KIND=4), DIMENSION(knumber),    INTENT(out  ) :: kimin, kimax, kjmin, kjmax
+
+    ! Local variables
+    INTEGER(KIND=4)                                       :: jsec
+    INTEGER(KIND=4)                                       :: ii, inum=10
+    INTEGER(KIND=4)                                       :: ipos  
+    CHARACTER(LEN=256)                                    :: cline
+    CHARACTER(LEN=80), DIMENSION(3)                       :: cldum
+    LOGICAL                                               :: llfirst
+    !!----------------------------------------------------------------------
+    llfirst=.FALSE.
+    IF ( knumber == 0 ) llfirst=.TRUE.
+
+    OPEN(inum, FILE=cdfile)
+    REWIND(inum)
+    ii = 0
+
+    ! read the file just to count the number of sections
+    DO
+       READ(inum,'(a)') cline
+       IF (INDEX(cline,'EOF') == 0 ) THEN
+          READ(inum,*)    ! skip one line
+          ii = ii + 1
+       ELSE
+          EXIT
+       ENDIF
+    END DO
+
+    knumber=ii
+    IF ( llfirst ) RETURN
+
+    REWIND(inum)
+    DO jsec=1,knumber
+       READ(inum,'(a)') cline
+       ii = 0
+       cldum(:) = 'none'
+       ipos = INDEX(cline,' ')
+       DO WHILE ( ipos > 1 ) 
+          ii = ii + 1
+          cldum(ii) = cline(1:ipos - 1 )
+          cline = TRIM ( cline(ipos+1:) )
+          ipos  = INDEX( cline,' ' ) 
+          IF ( ii >= 3 ) EXIT
+       END DO
+       cdsection(jsec) = TRIM(cldum(1) )
+       cdvarname(jsec) = TRIM(cldum(2) )
+       cdlongname(jsec) = TRIM(cldum(3) )
+       READ(inum,*    ) kimin(jsec), kimax(jsec), kjmin(jsec), kjmax(jsec)
+    END DO
+
+    CLOSE(inum)
+
+  END SUBROUTINE section_init
+
+  SUBROUTINE bimg_writ( ksec)
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE bimg_writ  ***
+    !!
+    !! ** Purpose :  Write output bimg files if required 
+    !!
+    !! ** Method  :  Most of the variables are global 
+    !!
+    !!----------------------------------------------------------------------
+    INTEGER(KIND=4), INTENT(in) :: ksec  ! number of the section
+
+    INTEGER(KIND=4)             :: ji, jk
+    !!----------------------------------------------------------------------
+    ! (along section, depth ) 2D variables
+    cf_bimg=TRIM(csection(ksec))//'_trpdep.bimg'
+    OPEN(numbimg,FILE=cf_bimg,FORM='UNFORMATTED')
+    cldum=' 4 dimensions in this isopycnal file '
+    WRITE(numbimg) cldum
+
+    cldum=' 1: T ;  2: S ; 3: sigma ; 4: Velocity '
+    WRITE(numbimg) cldum
+
+    WRITE(cldum,'(a,4i5.4)') ' from '//TRIM(csection(ksec)), iimin,iimax,ijmin,ijmax
+    WRITE(numbimg) cldum
+
+    cldum=' file '//TRIM(cf_brfi)
+    WRITE(numbimg) cldum
+
+    WRITE(numbimg) npts,nk,1,1,4,0
+    WRITE(numbimg) 1.,-float(nk),1.,1., 0.
+    WRITE(numbimg) 0.
+    WRITE(numbimg) 0.
+
+    WRITE(numbimg) (( REAL(zt(ji,jk)  ), ji=1,npts), jk=nk,1,-1 ) ! temperature 
+    WRITE(numbimg) (( REAL(zs(ji,jk)  ), ji=1,npts), jk=nk,1,-1 ) ! salinity
+    WRITE(numbimg) (( REAL(dsig(ji,jk)), ji=1,npts), jk=nk,1,-1 ) ! density
+    WRITE(numbimg) (( REAL(zu(ji,jk)  ), ji=1,npts), jk=nk,1,-1 ) ! normal velocity
+    CLOSE(numbimg)
+
+    ! (along section, sigma ) 2D variables
+    cf_bimg=TRIM(csection(ksec))//'_trpsig.bimg'
+    OPEN(numbimg,FILE=cf_bimg,FORM='UNFORMATTED')
+    cldum=' 3 dimensions in this isopycnal file '
+    WRITE(numbimg) cldum
+    cldum=' 1: hiso ;  2: bin trp ; 3: cumulated  trp '
+    WRITE(numbimg) cldum
+    WRITE(cldum,'(a,4i5.4)') ' from '//TRIM(csection(ksec)), iimin,iimax,ijmin,ijmax
+    WRITE(numbimg) cldum
+    cldum=' file '//TRIM(cf_brfi)
+    WRITE(numbimg) cldum
+    WRITE(numbimg) npts,nbins,1,1,3,0
+    WRITE(numbimg) 1.,-REAL(dsigma_lev(nbins)),1.,REAL(dltsig), 0.
+    WRITE(numbimg) 0.
+    WRITE(numbimg) 0.
+    WRITE(numbimg) (( REAL(dhiso(ji,jiso)   ),      ji=1,npts), jiso=nbins,1,-1) ! isopyc depth
+    WRITE(numbimg) (( REAL(dwtrpbin(ji,jiso))/1.e6, ji=1,npts), jiso=nbins,1,-1) ! binned transport
+    WRITE(numbimg) (( REAL(dwtrp(ji,jiso)   )/1.e6, ji=1,npts), jiso=nbins,1,-1) ! cumulated transport
+    CLOSE(numbimg)
+
+  END SUBROUTINE bimg_writ
+
+  SUBROUTINE cdf_writ( ksec)
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE cdf_writ  ***
+    !!
+    !! ** Purpose :  Write output cdf files if required 
+    !!
+    !! ** Method  :  Most of the variables are global 
+    !!
+    !!----------------------------------------------------------------------
+    INTEGER(KIND=4),   INTENT(in) :: ksec  ! number of the section
+
+    INTEGER(KIND=4)               :: ji, jk
+    INTEGER(KIND=4)               :: ivar
+    INTEGER(KIND=4)               :: icout
+    INTEGER(KIND=4), DIMENSION(4) :: ipk, id_varout
+
+    REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zdum
+    TYPE(variable),  DIMENSION(4) :: sl_typvar
+    CHARACTER(LEN=255)            :: csuffixvarnam
+    CHARACTER(LEN=255)            :: cprefixlongnam
+    !!----------------------------------------------------------------------
+    IF ( cvarname(ksec) /= 'none' ) THEN
+       csuffixvarnam = '_'//TRIM(cvarname(ksec))
+    ELSE
+       csuffixvarnam = ''
+    ENDIF
+    IF ( clongname(ksec) /= 'none' ) THEN
+       cprefixlongnam = TRIM(clongname(ksec))//'_'
+    ELSE
+       cprefixlongnam = ''
+    ENDIF
+
+    ALLOCATE ( zdum(npts,1))
+    ! (along section, depth ) 2D variables
+    cf_nc=TRIM(csection(ksec))//'_secdep.nc'
+    ! define variables
+    ipk(:)=nk
+    sl_typvar%rmissing_value    = 0.
+    sl_typvar%rmissing_value    = 0.
+    sl_typvar%scale_factor      = 1.
+    sl_typvar%add_offset        = 0.
+    sl_typvar%savelog10         = 0.
+    sl_typvar%iwght             = iweight
+    sl_typvar%conline_operation = 'N/A'
+    sl_typvar%caxis             = 'XZT'
+
+    ivar=1
+    sl_typvar(ivar)%cname          = 'temperature'//TRIM(csuffixvarnam)
+    sl_typvar(ivar)%cunits         = 'Celsius'
+    sl_typvar(ivar)%valid_min      = -2.
+    sl_typvar(ivar)%valid_max      = 45.
+    sl_typvar(ivar)%clong_name     = TRIM(cprefixlongnam)//'Potential_temperature'
+    sl_typvar(ivar)%cshort_name    = 'temperature'
+
+    ivar=ivar+1
+    sl_typvar(ivar)%cname          = 'salinity'//TRIM(csuffixvarnam)
+    sl_typvar(ivar)%cunits         = 'PSU'
+    sl_typvar(ivar)%valid_min      = 0.
+    sl_typvar(ivar)%valid_max      = 45.
+    sl_typvar(ivar)%clong_name     = TRIM(cprefixlongnam)//'Salinity'
+    sl_typvar(ivar)%cshort_name    = 'salinity'
+
+    ivar=ivar+1
+    sl_typvar(ivar)%cname          = 'density'//TRIM(csuffixvarnam)
+    sl_typvar(ivar)%cunits         = 'kg/m3 -1000'
+    sl_typvar(ivar)%valid_min      = 0.
+    sl_typvar(ivar)%valid_max      = 45.
+    sl_typvar(ivar)%clong_name     = TRIM(cprefixlongnam)//'potential_density'
+    sl_typvar(ivar)%cshort_name    = 'density'
+
+    ivar=ivar+1
+    sl_typvar(ivar)%cname          = 'velocity'//TRIM(csuffixvarnam)
+    sl_typvar(ivar)%cunits         = 'm/s'
+    sl_typvar(ivar)%valid_min      = -3.
+    sl_typvar(ivar)%valid_max      = 3.
+    sl_typvar(ivar)%clong_name     = TRIM(cprefixlongnam)//'Normal_velocity'
+    sl_typvar(ivar)%cshort_name    = 'velocity'
+
+    icout = create      (cf_nc, 'none',    npts, 1, nk, cdep=cn_vdeptht                     )
+    ierr  = createvar   (icout, sl_typvar, ivar, ipk, id_varout, cdglobal=TRIM(cglobal)     )
+    ierr  = putheadervar(icout, cf_brfi,   npts, 1, nk, &
+         &   pnavlon=rlonlat, pnavlat=rlonlat, cdep=cn_vdeptht                              )
+
+    !    tim  = getvar1d(cf_brfi, cn_vtimec, 1     )
+    !    ierr = putvar1d(icout,   tim,       1, 'T')
+
+    DO jk = 1, nk
+       zdum(:,1)=zt(:,jk)   ; ierr = putvar ( icout, id_varout(1), zdum, jk, npts, 1 )
+       zdum(:,1)=zs(:,jk)   ; ierr = putvar ( icout, id_varout(2), zdum, jk, npts, 1 )
+       zdum(:,1)=dsig(:,jk) ; ierr = putvar ( icout, id_varout(3), zdum, jk, npts, 1 )
+       zdum(:,1)=zu(:,jk)   ; ierr = putvar ( icout, id_varout(4), zdum, jk, npts, 1 )
+    END DO
+
+    ierr = closeout(icout)
+
+    ! (along section, sigma ) 2D variables
+    cf_nc=TRIM(csection(ksec))//'_secsig.nc'
+    ! define variables
+    ipk(:)=nbins
+    sl_typvar%rmissing_value    = 99999.
+    sl_typvar%rmissing_value    = 99999.
+    sl_typvar%scale_factor      = 1.
+    sl_typvar%add_offset        = 0.
+    sl_typvar%savelog10         = 0.
+    sl_typvar%iwght             = iweight
+    sl_typvar%conline_operation = 'N/A'
+    sl_typvar%caxis             = 'XST'
+
+    ivar=1
+    ipk(ivar)=nbins-1
+    sl_typvar(ivar)%cname          = 'isodep'//TRIM(csuffixvarnam)
+    sl_typvar(ivar)%cunits         = 'm'
+    sl_typvar(ivar)%valid_min      = 0.
+    sl_typvar(ivar)%valid_max      = 6000.
+    sl_typvar(ivar)%clong_name     = TRIM(cprefixlongnam)//'isopycnal_depth'
+    sl_typvar(ivar)%cshort_name    = 'isodep'
+
+    ivar=ivar+1
+    sl_typvar(ivar)%cname          = 'bintrp'//TRIM(csuffixvarnam)
+    sl_typvar(ivar)%cunits         = 'SV'
+    sl_typvar(ivar)%valid_min      = -5.
+    sl_typvar(ivar)%valid_max      = 5.
+    sl_typvar(ivar)%clong_name     = TRIM(cprefixlongnam)//'Binned_transport'
+    sl_typvar(ivar)%cshort_name    = 'bintrp'
+
+    ivar=ivar+1
+    sl_typvar(ivar)%cname          = 'sumtrp'//TRIM(csuffixvarnam)
+    sl_typvar(ivar)%cunits         = 'SV'
+    sl_typvar(ivar)%valid_min      = -20.
+    sl_typvar(ivar)%valid_max      = 20.
+    sl_typvar(ivar)%clong_name     = TRIM(cprefixlongnam)//'cumulated_transport'
+    sl_typvar(ivar)%cshort_name    = 'sumtrp'
+
+    icout = create      (cf_nc, 'none',    npts, 1, nbins, cdep='levels'                 )
+    ierr  = createvar   (icout, sl_typvar, ivar, ipk, id_varout, cdglobal=TRIM(cglobal)  )
+    ierr  = putheadervar(icout, cf_brfi,   npts, 1, nbins, &
+         &   pnavlon=rlonlat, pnavlat=rlonlat, pdep=REAL(dsigma_lev), cdep='levels'      )
+
+    PRINT *, 'NBINS', nbins, npts
+    DO jk = 1, nbins-1
+       zdum(:,1)=dhiso   (:,jk)      ; ierr = putvar ( icout, id_varout(1), zdum, jk, npts, 1 )
+    END DO
+    DO jk = 1, nbins
+       zdum(:,1)=dwtrpbin(:,jk)/1.e6 ; ierr = putvar ( icout, id_varout(2), zdum, jk, npts, 1 )
+       zdum(:,1)=dwtrp   (:,jk)/1.e6 ; ierr = putvar ( icout, id_varout(3), zdum, jk, npts, 1 )
+    END DO
+    ierr = closeout(icout)
+
+    DEALLOCATE ( zdum )
+
+  END SUBROUTINE cdf_writ
+
+  SUBROUTINE print_out(ksec)
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE print_out  ***
+    !!
+    !! ** Purpose :  Print results on standard output 
+    !!
+    !! ** Method  :  Most of the variables are global and already known 
+    !!
+    !!----------------------------------------------------------------------
+    INTEGER(KIND=4), INTENT(in) :: ksec  ! number of the section
+
+    INTEGER(KIND=4)             :: ji, jk, jiso, jbin
+    !!----------------------------------------------------------------------
+    WRITE(cfmt_9000,'(a,i4,a)') '(i7,  ',npts,'f8.3)'
+    WRITE(cfmt_9001,'(a,i4,a)') '(i7,  ',npts,'f8.0)'
+    WRITE(cfmt_9002,'(a,i4,a)') '(f7.3,',npts,'f8.0)'
+    WRITE(cfmt_9003,'(a,i4,a)') '(f7.3,',npts,'f8.3)'
+    PRINT *,' T (deg C)' 
+    DO jk=1,nk
+       PRINT cfmt_9000, jk,  (zt(ji,jk),ji=1,npts)
+    END DO
+
+    PRINT *,' S (PSU)'
+    DO jk=1,nk
+       PRINT cfmt_9000,  jk,  (zs(ji,jk),ji=1,npts)
+    END DO
+
+    PRINT *,' SIG (kg/m3 - 1000 )'
+    DO jk=1,nk
+       PRINT cfmt_9000, jk,  (dsig(ji,jk),ji=1,npts)
+    END DO
+
+    PRINT *,' VELOCITY (cm/s ) '
+    DO jk=1,nk
+       PRINT cfmt_9000, jk,  (zu(ji,jk)*100,ji=1,npts)
+    END DO
+
+    PRINT *,' GDEPU (m) '
+    DO jk=1,nk
+       PRINT cfmt_9001,jk,  (ddepu(ji,jk)*zmask(ji,jk),ji=1,npts)
+    END DO
+
+    PRINT *, 'E3 (m)'
+    DO jk=1,nk
+       PRINT cfmt_9001,jk,  (de3(ji,jk)*zmask(ji,jk),ji=1,npts)
+    END DO
+
+    PRINT *,' DEP ISO ( m )'
+    DO  jiso =1, nbins+1
+       PRINT cfmt_9002, dsigma_lev(jiso),(dhiso(ji,jiso),ji=1,npts)
+    END DO
+
+    PRINT *,' TRP SURF -->  ISO (SV)'
+    DO  jiso =1, nbins+1
+       PRINT  cfmt_9003, dsigma_lev(jiso),(dwtrp(ji,jiso)/1.d6,ji=1,npts)
+    END DO
+
+    PRINT *,' TRP bins (SV)'
+    DO  jbin =1, nbins
+       PRINT  cfmt_9003, dsigma_lev(jbin),(dwtrpbin(ji,jbin)/1.d6,ji=1,npts), dtrpbin(ksec,jbin)/1.d6
+    END DO
+
+
+
+  END SUBROUTINE print_out
+
+END PROGRAM cdfsigtrp_broken
diff --git a/cdfsigtrp.f90 b/src/cdfsigtrp_broken2.f90
similarity index 86%
rename from cdfsigtrp.f90
rename to src/cdfsigtrp_broken2.f90
index e298afa..4ca9989 100644
--- a/cdfsigtrp.f90
+++ b/src/cdfsigtrp_broken2.f90
@@ -1,9 +1,9 @@
-PROGRAM cdfsigtrp
+PROGRAM cdfsigtrp_broken
    !!======================================================================
    !!                     ***  PROGRAM  cdfsigtrp  ***
    !!======================================================================
    !!  ** Purpose : Compute density class Mass transport across a section.
-   !!
+   !!           
    !!  ** Method  :- The begining and end point of the section are given in 
    !!                term of f-points index.
    !!              - The program works for zonal or meridional sections.
@@ -40,7 +40,7 @@ PROGRAM cdfsigtrp
    USE modutils     ! for SetGlobalAtt
    !!----------------------------------------------------------------------
    !! CDFTOOLS_3.0 , MEOM 2011
-   !! $Id$
+   !! $Id: cdfsigtrp.f90 699 2013-06-24 14:17:21Z molines $
    !! Copyright (c) 2011, J.-M. Molines
    !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
    !!----------------------------------------------------------------------
@@ -79,7 +79,7 @@ PROGRAM cdfsigtrp
    REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: zu                   ! velocity
    REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: zmask                ! mask
    REAL(KIND=4), DIMENSION(:,:,:),   ALLOCATABLE :: tmpm, tmpz           ! temporary arrays
-
+   REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: tmpz1d               ! temporary arrays
    ! double precision for cumulative variables and densities
    REAL(KIND=8)                                  :: dsigma_min           ! minimum density for bining
    REAL(KIND=8)                                  :: dsigma_max, dltsig   ! maximum density for bining, step
@@ -94,9 +94,9 @@ PROGRAM cdfsigtrp
 
    TYPE(variable), DIMENSION(:),     ALLOCATABLE :: stypvar              ! structure of output
 
-   CHARACTER(LEN=256)                            :: cf_tfil              ! temperature salinity file
-   CHARACTER(LEN=256)                            :: cf_ufil              ! zonal velocity file
-   CHARACTER(LEN=256)                            :: cf_vfil              ! meridional velocity file
+   CHARACTER(LEN=256)                            :: cf_tfil              ! temperature salinity velocity file
+   !CHARACTER(LEN=256)                            :: cf_ufil              ! zonal velocity file
+   !CHARACTER(LEN=256)                            :: cf_vfil              ! meridional velocity file
    CHARACTER(LEN=256)                            :: cf_section='dens_section.dat'  ! input section file
    CHARACTER(LEN=256)                            :: cf_out='trpsig.txt'  ! output  ascii file
    CHARACTER(LEN=256)                            :: cf_bimg              ! output bimg file (2d)
@@ -118,20 +118,21 @@ PROGRAM cdfsigtrp
    CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: clongname            ! output long name (root)
 
    LOGICAL                                       :: l_merid              ! flag for meridional section
-   LOGICAL                                       :: ltemp  =.FALSE.      ! flag for extra print
+   LOGICAL                                       :: ltemp  =.FALSE.      ! flag for use of temperature
    LOGICAL                                       :: lprint =.FALSE.      ! flag for extra print
    LOGICAL                                       :: lbimg  =.FALSE.      ! flag for bimg output
-   LOGICAL                                       :: lncdf  =.FALSE.      ! flag for bimg output
-   LOGICAL                                       :: lfull  =.FALSE.      ! flag for bimg output
+   LOGICAL                                       :: lncdf  =.FALSE.      ! flag for extra netcdf output
+   LOGICAL                                       :: lfull  =.FALSE.      ! flag for full step 
+   LOGICAL                                       :: lneutral  =.FALSE.   ! flag for neutral density
    LOGICAL                                       :: lchk   =.FALSE.      ! flag for missing files
    !!----------------------------------------------------------------------
    CALL ReadCdfNames()
 
    narg= iargc()
-   IF ( narg < 6 ) THEN
-      PRINT *,' usage :  cdfsigtrp T-file U-file V-file sigma_min sigma_max nbins ...'
+   IF ( narg < 4 ) THEN
+      PRINT *,' usage :  cdfsigtrp_broken TSV-file sigma_min sigma_max nbins ...'
       PRINT *,'              ... [-print ] [-bimg ] [-full ] [ -refdep ref_depth] ...'
-      PRINT *,'              ... [-section file ] [-temp ]'
+      PRINT *,'              ... [-neutral ] [-section file ] [-temp ]'
       PRINT *,'      '
       PRINT *,'     PURPOSE :'
       PRINT *,'       Compute density class transports, according to the density class' 
@@ -143,16 +144,18 @@ PROGRAM cdfsigtrp
       PRINT *,'       it differs from the standard name. Optionaly, a netcdf root variable '
       PRINT *,'       name and a netcdf root long-name can be provided on the line giving '
       PRINT *,'       the section name.'
+      PRINT *,'       Pedro: The section used is the result of cdf_xtrac_broken. In this way,'
+      PRINT *,'       it is possible to calculate the transport of density class in'
+      PRINT *,'       oblicous sections (non dependance on zonal or meridional).'
       PRINT *,'      '
       PRINT *,'       This program can also be used to compute transport by class of '
-      PRINT *,'       temperatures, provided the temperatures decreases monotonically '
+      PRINT *,'       temperatures, provided the temperatures decrease monotonically '
       PRINT *,'       downward. In this case, use -temp option and of course specify'
       PRINT *,'       sigma_min, sigma_max as temperatures.'
       PRINT *,'      '
       PRINT *,'     ARGUMENTS :'
-      PRINT *,'       T-file : netcdf file with temperature and salinity' 
-      PRINT *,'       U-file : netcdf file with zonal velocity component'
-      PRINT *,'       V-file : netcdf file with meridional velocity component'
+      PRINT *,'       TSV-file : netcdf_broken_line file with temperature, salinity' 
+      PRINT *,'       and the normal velocity through the section'
       PRINT *,'       sigma_min : minimum density for binning'
       PRINT *,'       sigma_max : maximum density for binning'
       PRINT *,'       nbins : number of bins. This will fix the bin ''width'' '
@@ -171,6 +174,7 @@ PROGRAM cdfsigtrp
       PRINT *,'       [ -refdep ref_depth ]: give a reference depths for the computation of'
       PRINT *,'               potential density. Sigma_min, sigma_max must be adapted '
       PRINT *,'               accordingly.'
+      PRINT *,'       [ -neutral ]: use neutral density instead of potential density '
       PRINT *,'       [ -section file] : give the name of section file.'
       PRINT *,'               Default is ', TRIM(cf_section)
       PRINT *,'       [ -temp ] : use temperature instead of density for binning'
@@ -211,28 +215,29 @@ PROGRAM cdfsigtrp
       CASE ( '-temp')  ; ltemp  = .TRUE. 
       CASE ( '-refdep' ) ; CALL getarg(ijarg, cldum      ) ; ijarg=ijarg+1 ; READ(cldum,*) refdep
       CASE ( '-section') ; CALL getarg(ijarg, cf_section ) ; ijarg=ijarg+1 
+      CASE ( '-neutral') ; lneutral = .TRUE.
       CASE DEFAULT
          ireq=ireq+1
          SELECT CASE ( ireq)
          CASE ( 1 ) ; cf_tfil = cldum
-         CASE ( 2 ) ; cf_ufil = cldum
-         CASE ( 3 ) ; cf_vfil = cldum
-         CASE ( 4 ) ; READ(cldum,*) dsigma_min
-         CASE ( 5 ) ; READ(cldum,*) dsigma_max
-         CASE ( 6 ) ; READ(cldum,*) nbins
+         !CASE ( 2 ) ; cf_ufil = cldum
+         !CASE ( 3 ) ; cf_vfil = cldum
+         CASE ( 2 ) ; READ(cldum,*) dsigma_min
+         CASE ( 3 ) ; READ(cldum,*) dsigma_max
+         CASE ( 4 ) ; READ(cldum,*) nbins
          CASE DEFAULT 
             PRINT *,' Too many arguments ' ; STOP
          END SELECT
       END SELECT
    END DO
-
+   !Commented Pedro
    ! check for file existence
    lchk = lchk .OR. chkfile( cn_fzgr    )
    lchk = lchk .OR. chkfile( cn_fhgr    )
    lchk = lchk .OR. chkfile( cf_section )
    lchk = lchk .OR. chkfile( cf_tfil    )
-   lchk = lchk .OR. chkfile( cf_ufil    )
-   lchk = lchk .OR. chkfile( cf_vfil    )
+   !lchk = lchk .OR. chkfile( cf_ufil    )
+   !lchk = lchk .OR. chkfile( cf_vfil    )
    IF ( lchk ) STOP ! missing file
    IF ( ltemp)  THEN  ! temperature decrease downward. Change sign and swap min/max
       refdep = -10. ! flag value
@@ -244,8 +249,10 @@ PROGRAM cdfsigtrp
    ! define global attribute with command line
    CALL SetGlobalAtt( cglobal)
 
+   !! Commented Pedro   
    ! get the attribute iweight from vozocrtx
-   iweight = getatt(cf_ufil, cn_vozocrtx, 'iweight')
+   !iweight = getatt(cf_ufil, cn_vozocrtx, 'iweight')
+   iweight = 1
    IF ( iweight == 0 ) iweight = 1  ! if 0 means that it is not defined.
 
    ALLOCATE ( stypvar(nboutput), ipk(nboutput), id_varout(nboutput) )
@@ -313,63 +320,65 @@ PROGRAM cdfsigtrp
       ALLOCATE ( dwtrp(npts, nbins+1), dhiso(npts,nbins+1), dwtrpbin(npts,nbins) )
       ALLOCATE ( rlonlat(npts,1) )
 
-      zt = 0. ; zs = 0. ; zu = 0. ; ddepu= 0. ; zmask = 0.  ; dsig=0.d0
 
       IF (l_merid ) THEN   ! meridional section at i=iimin=iimax
-         tmpm(:,:,1)   = getvar(cn_fhgr, cn_ve2u,   1, 1, npts, kimin=iimin, kjmin=ijmin+1)
-         eu(:)         = tmpm(1,:,1)  ! metrics varies only horizontally
-         tmpm(:,:,1)   = getvar(cn_fhgr, cn_vlat2d, 1, 1, npts, kimin=iimin, kjmin=ijmin+1)
-         rlonlat(:,1)  = tmpm(1,:,1)  ! latitude in this case
-         DO jk = 1,npk
-            ! initiliaze ddepu to gdept()
-            ddepu(:,jk) = gdept(jk)
-
-            IF ( lfull ) THEN
-               de3(:,jk)   = e3t1d(jk)
-               tmpm(1,:,1) = e3w1d(jk)
-               tmpm(1,:,2) = e3w1d(jk)
-            ELSE
-               ! vertical metrics (PS case)
-               tmpm(:,:,1) = getvar(cn_fzgr, 'e3u_ps', jk, 1, npts, kimin=iimin,   kjmin=ijmin+1, ldiom=.TRUE.)
-               de3(:,jk)   = tmpm(1,:,1)
-               tmpm(:,:,1) = getvar(cn_fzgr, 'e3w_ps', jk, 1, npts, kimin=iimin,   kjmin=ijmin+1, ldiom=.TRUE.)
-               tmpm(:,:,2) = getvar(cn_fzgr, 'e3w_ps', jk, 1, npts, kimin=iimin+1, kjmin=ijmin+1, ldiom=.TRUE.)
-            ENDIF
-
-            IF (jk >= 2 ) THEN
-               DO ji=1,npts
-                  ddepu(ji,jk)= ddepu(ji,jk-1) + MIN(tmpm(1,ji,1), tmpm(1,ji,2))
-               END DO
-            ENDIF
-
-            ! Normal velocity
-            tmpm(:,:,1) = getvar(cf_ufil,cn_vozocrtx,jk,1,npts, kimin=iimin, kjmin=ijmin+1)
-            zu(:,jk)    = tmpm(1,:,1)
-
-            ! salinity and deduce umask for the section
-            tmpm(:,:,1) = getvar(cf_tfil,cn_vosaline,jk,1,npts, kimin=iimin  , kjmin=ijmin+1)
-            tmpm(:,:,2) = getvar(cf_tfil,cn_vosaline,jk,1,npts, kimin=iimin+1, kjmin=ijmin+1)
-            zmask(:,jk) = tmpm(1,:,1)*tmpm(1,:,2)
-            WHERE ( zmask(:,jk) /= 0 ) zmask(:,jk)=1
+         EXIT
+      !   tmpm(:,:,1)   = getvar(cn_fhgr, cn_ve2u,   1, 1, npts, kimin=iimin, kjmin=ijmin+1)
+      !   eu(:)         = tmpm(1,:,1)  ! metrics varies only horizontally
+      !   tmpm(:,:,1)   = getvar(cn_fhgr, cn_vlat2d, 1, 1, npts, kimin=iimin, kjmin=ijmin+1)
+      !   rlonlat(:,1)  = tmpm(1,:,1)  ! latitude in this case
+      !   DO jk = 1,npk
+      !      ! initiliaze ddepu to gdept()
+      !      ddepu(:,jk) = gdept(jk)
+
+      !      IF ( lfull ) THEN
+      !         de3(:,jk)   = e3t1d(jk)
+      !         tmpm(1,:,1) = e3w1d(jk)
+      !         tmpm(1,:,2) = e3w1d(jk)
+      !      ELSE
+      !         ! vertical metrics (PS case)
+      !         tmpm(:,:,1) = getvar(cf_ufil, 'e3u_ps', jk, 1, npts, kimin=iimin,   kjmin=ijmin+1, ldiom=.TRUE.)
+      !         de3(:,jk)   = tmpm(1,:,1)
+      !         tmpm(:,:,1) = getvar(cf_ufil, 'e3w_ps', jk, 1, npts, kimin=iimin,   kjmin=ijmin+1, ldiom=.TRUE.)
+      !         tmpm(:,:,2) = getvar(cf_ufil, 'e3w_ps', jk, 1, npts, kimin=iimin+1, kjmin=ijmin+1, ldiom=.TRUE.)
+      !      ENDIF
+
+      !      IF (jk >= 2 ) THEN
+      !         DO ji=1,npts
+      !            ddepu(ji,jk)= ddepu(ji,jk-1) + MIN(tmpm(1,ji,1), tmpm(1,ji,2))
+      !         END DO
+      !      ENDIF
+
+      !      ! Normal velocity
+      !      tmpm(:,:,1) = getvar(cf_ufil,cn_vozocrtx,jk,1,npts, kimin=iimin, kjmin=ijmin+1)
+      !      zu(:,jk)    = tmpm(1,:,1)
+
+      !      ! salinity and deduce umask for the section
+      !      tmpm(:,:,1) = getvar(cf_tfil,cn_vosaline,jk,1,npts, kimin=iimin  , kjmin=ijmin+1)
+      !      tmpm(:,:,2) = getvar(cf_tfil,cn_vosaline,jk,1,npts, kimin=iimin+1, kjmin=ijmin+1)
+      !      zmask(:,jk) = tmpm(1,:,1)*tmpm(1,:,2)
+      !      WHERE ( zmask(:,jk) /= 0 ) zmask(:,jk)=1
             ! do not take special care for land value, as the corresponding velocity point is masked
-            zs(:,jk) = 0.5 * ( tmpm(1,:,1) + tmpm(1,:,2) )
-
-            ! limitation to 'wet' points
-            IF ( SUM(zs(:,jk))  == 0 ) THEN
-               nk=jk ! first vertical point of the section full on land
-               EXIT  ! as soon as all the points are on land
-            ENDIF
-
-            ! temperature
-            tmpm(:,:,1) = getvar(cf_tfil, cn_votemper, jk, 1, npts, kimin=iimin,   kjmin=ijmin+1)
-            tmpm(:,:,2) = getvar(cf_tfil, cn_votemper, jk, 1, npts, kimin=iimin+1, kjmin=ijmin+1)
-            zt(:,jk) = 0.5 * ( tmpm(1,:,1) + tmpm(1,:,2) )
-         END DO
-
-      ELSE                   ! zonal section at j=ijmin=ijmax
-         tmpz(:,:,1)  = getvar(cn_fhgr, cn_ve1v,   1, npts, 1, kimin=iimin, kjmin=ijmin)
+      !      zs(:,jk) = 0.5 * ( tmpm(1,:,1) + tmpm(1,:,2) )
+
+      !      ! limitation to 'wet' points
+      !      IF ( SUM(zs(:,jk))  == 0 ) THEN
+      !         nk=jk ! first vertical point of the section full on land
+      !         EXIT  ! as soon as all the points are on land
+      !      ENDIF
+
+      !      ! temperature
+      !      tmpm(:,:,1) = getvar(cf_ufil, cn_votemper, jk, 1, npts, kimin=iimin,   kjmin=ijmin+1)
+      !      tmpm(:,:,2) = getvar(cf_ufil, cn_votemper, jk, 1, npts, kimin=iimin+1, kjmin=ijmin+1)
+      !      zt(:,jk) = 0.5 * ( tmpm(1,:,1) + tmpm(1,:,2) )
+      !   END DO
+
+      ELSE                !!Commented Pedro
+         ! zonal section at j=ijmin=ijmax
+         !tmpz(:,:,1)  = getvar(cn_fhgr, cn_ve1v,   1, npts, 1, kimin=iimin, kjmin=ijmin)
+         tmpz(:,:,1)  = getvar(cf_tfil, cn_ve1v,   1, npts, 1, kimin=iimin, kjmin=ijmin)
          eu(:)        = tmpz(:,1,1)
-         tmpz(:,:,1)  = getvar(cn_fhgr, cn_vlon2d, 1, npts, 1, kimin=iimin, kjmin=ijmin)
+         tmpz(:,:,1)  = getvar(cf_tfil, cn_vlon2d, 1, npts, 1, kimin=iimin, kjmin=ijmin)
          rlonlat(:,1) = tmpz(:,1,1)  ! longitude in this case
          DO jk=1,npk
             ! initiliaze ddepu to gdept()
@@ -380,52 +389,60 @@ PROGRAM cdfsigtrp
                tmpm(:,1,1) = e3w1d(jk)
                tmpm(:,1,2) = e3w1d(jk)
             ELSE
+               !!Commented Pedro
                ! vertical metrics (PS case)
-               tmpz(:,:,1)=getvar(cn_fzgr,'e3v_ps',jk, npts, 1, kimin=iimin+1, kjmin=ijmin, ldiom=.TRUE.)
+               !tmpz(:,:,1)=getvar(cn_fzgr,'e3v_ps',jk, npts, 1, kimin=iimin+1, kjmin=ijmin, ldiom=.TRUE.)
+               tmpz(:,:,1)=getvar(cf_tfil,'e3v_ps',jk, npts, 1, kimin=iimin+1, kjmin=ijmin, ldiom=.TRUE.)
                de3(:,jk) = tmpz(:,1,1)
-               tmpz(:,:,1)=getvar(cn_fzgr,'e3w_ps',jk,npts,1, kimin=iimin+1, kjmin=ijmin,   ldiom=.TRUE.)
-               tmpz(:,:,2)=getvar(cn_fzgr,'e3w_ps',jk,npts,1, kimin=iimin+1, kjmin=ijmin+1, ldiom=.TRUE.)
+               !tmpz(:,:,1)=getvar(cn_fzgr,'e3w_ps',jk,npts,1, kimin=iimin+1, kjmin=ijmin,   ldiom=.TRUE.)
+               !tmpz(:,:,2)=getvar(cn_fzgr,'e3w_ps',jk,npts,1, kimin=iimin+1, kjmin=ijmin+1, ldiom=.TRUE.)
             ENDIF
-
+            !!Commented Pedro
             IF (jk >= 2 ) THEN
                DO ji=1,npts
-                  ddepu(ji,jk)= ddepu(ji,jk-1) + MIN(tmpz(ji,1,1), tmpz(ji,1,2))
+                  ddepu(ji,jk)= ddepu(ji,jk-1) + tmpz(ji,1,1)!MIN(tmpz(ji,1,1), tmpz(ji,1,2))
                END DO
             ENDIF
 
             ! Normal velocity
-            tmpz(:,:,1)=getvar(cf_vfil,cn_vomecrty,jk,npts,1, kimin=iimin+1, kjmin=ijmin)
+            tmpz(:,:,1)=getvar(cf_tfil,cn_vomecrty,jk,npts,1, kimin=iimin+1, kjmin=ijmin)
             zu(:,jk)=tmpz(:,1,1)
-
+            !!Commented Pedro
             ! salinity and mask
-            tmpz(:,:,1)=getvar(cf_tfil,cn_vosaline,jk, npts, 1, kimin=iimin+1, kjmin=ijmin)
-            tmpz(:,:,2)=getvar(cf_tfil,cn_vosaline,jk, npts, 1, kimin=iimin+1, kjmin=ijmin+1)
-            zmask(:,jk)=tmpz(:,1,1)*tmpz(:,1,2)
+            !tmpz(:,:,2)=getvar(cf_tfil,cn_vosaline,jk, npts, 1, kimin=iimin+1, kjmin=ijmin+1)
+            tmpz(:,:,1)=getvar(cf_tfil,cn_vosaline,jk,npts,1, kimin=iimin+1, kjmin=ijmin)
+            zmask(:,jk)=tmpz(:,1,1)
             WHERE ( zmask(:,jk) /= 0 ) zmask(:,jk)=1
             ! do not take special care for land value, as the corresponding velocity point is masked
-            zs(:,jk) = 0.5 * ( tmpz(:,1,1) + tmpz(:,1,2) )
-
+            !zs(:,jk) = 0.5 * ( tmpz(:,1,1) + tmpz(:,1,2) )
+            zs(:,jk) = tmpz(:,1,1)
             ! limitation to 'wet' points
             IF ( SUM(zs(:,jk))  == 0 ) THEN
                nk=jk ! first vertical point of the section full on land
                EXIT  ! as soon as all the points are on land
             ENDIF
 
+            !!Commented Pedro
             ! temperature
             tmpz(:,:,1)=getvar(cf_tfil,cn_votemper,jk, npts, 1, kimin=iimin+1, kjmin=ijmin)
-            tmpz(:,:,2)=getvar(cf_tfil,cn_votemper,jk, npts, 1, kimin=iimin+1, kjmin=ijmin+1)
-            zt(:,jk) = 0.5 * ( tmpz(:,1,1) + tmpz(:,1,2) )
+            !tmpz(:,:,2)=getvar(cf_tfil,cn_votemper,jk, npts, 1, kimin=iimin+1, kjmin=ijmin+1)
+            !zt(:,jk) = 0.5 * ( tmpz(:,1,1) + tmpz(:,1,2) )
+            zt(:,jk) = tmpz(:,1,1)
          END DO
 
       ENDIF
-
+      !! Commented Pedro
       ! compute density only for wet points
-      IF ( refdep == -10. ) THEN
-         dsig(:,1:nk)= -zt(:,:)  ! change sign 
-      ELSEIF ( refdep == 0. ) THEN
-         dsig(:,1:nk)=sigma0( zt, zs,         npts, nk)*zmask(:,:)
+      IF ( lneutral ) THEN 
+         dsig(:,1:nk)=sigmantr( zt, zs,         npts, nk)*zmask(:,:)
       ELSE
-         dsig(:,1:nk)=sigmai( zt, zs, refdep, npts, nk)*zmask(:,:)
+        IF ( refdep == -10. ) THEN
+           dsig(:,1:nk)= -zt(:,:)  ! change sign 
+        ELSEIF ( refdep == 0. ) THEN
+           dsig(:,1:nk)=sigma0( zt, zs,         npts, nk)*zmask(:,:)
+        ELSE
+           dsig(:,1:nk)=sigmai( zt, zs, refdep, npts, nk)*zmask(:,:)
+        ENDIF
       ENDIF
 
       dsig(:,0)=dsig(:,1)-1.e-4   ! dummy layer for easy interpolation
@@ -939,4 +956,4 @@ CONTAINS
 
    END SUBROUTINE print_out
 
-END PROGRAM cdfsigtrp
+END PROGRAM cdfsigtrp_broken
diff --git a/cdfsmooth.f90 b/src/cdfsmooth.f90
similarity index 86%
rename from cdfsmooth.f90
rename to src/cdfsmooth.f90
index 122e65f..8f4af57 100644
--- a/cdfsmooth.f90
+++ b/src/cdfsmooth.f90
@@ -32,6 +32,7 @@ PROGRAM cdfsmooth
   !!----------------------------------------------------------------------
   USE cdfio
   USE modcdfnames
+  USE modutils
   !!----------------------------------------------------------------------
   !! CDFTOOLS_3.0 , MEOM 2011
   !! $Id$
@@ -46,19 +47,24 @@ PROGRAM cdfsmooth
   INTEGER(KIND=4), PARAMETER                    :: jp_boxc=4         ! box car id
   INTEGER(KIND=4)                               :: jk, jt, jvar      ! dummy loop index
   INTEGER(KIND=4)                               :: npiglo, npjglo    ! size of the domain
-  INTEGER(KIND=4)                               :: npk, npt          ! size of the domain
+  INTEGER(KIND=4)                               :: npk, npkf, npt    ! size of the domain
   INTEGER(KIND=4)                               :: narg, iargc       ! browse arguments
+  INTEGER(KIND=4)                               :: ijarg             ! argument index for browsing line
   INTEGER(KIND=4)                               :: ncut, nband       ! cut period/ length, bandwidth
   INTEGER(KIND=4)                               :: nfilter = jp_lanc ! default value
   INTEGER(KIND=4)                               :: nvars, ierr       ! number of vars
   INTEGER(KIND=4)                               :: ncout             ! ncid of output file
+  INTEGER(KIND=4)                               :: ilev              ! level to process if not 0
+  INTEGER(KIND=4)                               :: ijk               ! indirect level addressing
   INTEGER(KIND=4), DIMENSION(:,:),  ALLOCATABLE :: iw                ! flag for bad values (or land masked )
   INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_var            ! arrays of var id's
   INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: ipk               ! arrays of vertical level for each var
   INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_varout         ! id of output variables
+  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: iklist            ! list of k-level to process
 
   REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: v2d, w2d          ! raw data,  filtered result
   REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: tim               ! time array
+  REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: gdep, gdeptmp     ! depth array 
   REAL(KIND=4)                                  :: fn, rspval        ! cutoff freq/wavelength, spval
   REAL(KIND=4)                                  :: ranis             ! anistropy
 
@@ -72,12 +78,17 @@ PROGRAM cdfsmooth
   CHARACTER(LEN=256)                            :: cv_dep, cv_tim    ! variable name for depth and time
   CHARACTER(LEN=256)                            :: ctyp              ! filter type
   CHARACTER(LEN=256)                            :: cldum             ! dummy character variable
+  CHARACTER(LEN=256)                            :: clklist           ! ciphered k-list of level
+ 
+  LOGICAL                                       :: lnc4 = .false.    ! flag for netcdf4 output with chinking and deflation
+
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
   narg=iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfsmooth IN-file ncut [filter_type]'
+     PRINT *,' usage : cdfsmooth -f IN-file -c ncut [-t filter_type] [ -k level_list ] ...'
+     PRINT *,'       [-a anisotripoc ratio ] [-nc4 ] '
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
      PRINT *,'       Perform a spatial smoothing on the file using a particular'
@@ -86,16 +97,20 @@ PROGRAM cdfsmooth
      PRINT *,'       is Lanczos filter.'
      PRINT *,'      '
      PRINT *,'     ARGUMENTS :'
-     PRINT *,'        IN-file  : input data file. All variables will be filtered'
-     PRINT *,'        ncut     : number of grid step to be filtered, or number'
-     PRINT *,'                   of iteration of the Shapiro filter.'
+     PRINT *,'       -f  IN-file  : input data file. All variables will be filtered'
+     PRINT *,'       -c  ncut     : number of grid step to be filtered, or number'
+     PRINT *,'                    of iteration of the Shapiro filter.'
      PRINT *,'      '
      PRINT *,'     OPTIONS :'
-     PRINT *,'        [filter_type] : Lanczos      , L, l  (default)'
+     PRINT *,'       -t filter_type : Lanczos      , L, l  (default)'
      PRINT *,'                        Hanning      , H, h'
      PRINT *,'                        Shapiro      , S, s'
      PRINT *,'                        Box          , B, b'
-     PRINT *,'                        Anis. Box    , B, b + anisotropy ratio' 
+     PRINT *,'       -a aniso       : anisotropic ratio for Box car '
+     PRINT *,'       -k level_list  : levels to be filtered (default = all levels)'
+     PRINT *,'               level_list is a comma-separated list of levels.'
+     PRINT *,'                  the syntax 1-3,6,9-12 will select 1 2 3 6 9 10 11 12'
+     PRINT *,'       -nc4 : produce netcdf4 output file with chunking and deflation.'
      PRINT *,'      '
      PRINT *,'     OUTPUT : '
      PRINT *,'       Output file name is build from input file name with indication'
@@ -105,8 +120,26 @@ PROGRAM cdfsmooth
      STOP
   ENDIF
   !
-  CALL getarg(1,cf_in)
-  CALL getarg(2,cldum) ;  READ(cldum,*) ncut   
+  ijarg = 1
+  ilev  = 0
+  ranis = 1   ! anisotropic ratio for Box car filter
+  ctyp  = 'L'
+  ncut  = 0   ! hence program exit if none specified on command line
+  DO WHILE (ijarg <= narg )
+     CALL getarg ( ijarg, cldum ) ; ijarg=ijarg+1
+     SELECT CASE (cldum)
+     CASE ( '-f' ) ; CALL getarg ( ijarg, cf_in   ) ; ijarg=ijarg+1
+     CASE ( '-c' ) ; CALL getarg ( ijarg, cldum   ) ; ijarg=ijarg+1 ; READ(cldum,*) ncut
+     CASE ( '-t' ) ; CALL getarg ( ijarg, ctyp    ) ; ijarg=ijarg+1 
+     CASE ( '-k' ) ; CALL getarg ( ijarg, clklist ) ; ijarg=ijarg+1 
+          CALL GetList (clklist, iklist, ilev )
+     CASE ( '-a'  ) ; CALL getarg ( ijarg, cldum   ) ; ijarg=ijarg+1 ; READ(cldum,*) ranis
+     CASE ( '-nc4') ;  lnc4=.true.
+     END SELECT
+  ENDDO
+
+  IF ( ncut == 0 ) STOP ' cdfsmooth : ncut = 0 --> nothing to do !'
+
   IF ( chkfile(cf_in) ) STOP ! missing file
 
   !  remark: for a spatial filter, fn=dx/lambda where dx is spatial step, lamda is cutting wavelength
@@ -117,8 +150,6 @@ PROGRAM cdfsmooth
 
   WRITE(cf_out,'(a,a,i3.3)') TRIM(cf_in),'L',ncut   ! default name
 
-  IF ( narg  >= 3 ) THEN
-     CALL getarg(3,  ctyp)
      SELECT CASE ( ctyp)
      CASE ( 'Lanczos','L','l') 
         nfilter=jp_lanc
@@ -136,31 +167,31 @@ PROGRAM cdfsmooth
      CASE ( 'Box','B','b')
         nfilter=jp_boxc
         WRITE(cf_out,'(a,a,i3.3)') TRIM(cf_in),'B',ncut
-        PRINT *,' Working with Box filter'
+        IF ( ranis /=1. ) THEN
+          PRINT *, 'Anisotropic box car with ratio Lx = ', ranis, 'x Ly'
+        ELSE
+          PRINT *,' Working with Box filter'
+        ENDIF
      CASE DEFAULT
         PRINT *, TRIM(ctyp),' : undefined filter ' ; STOP
      END SELECT
-  ENDIF
-
-  IF ( narg  == 4 ) THEN
-     CALL getarg(4,cldum) ;  READ(cldum,*) ranis
-     PRINT *, 'Anisotropic box car with ratio Lx = ', ranis, 'x Ly'
-  ELSE
-     ranis=1.
-  ENDIF   
 
   CALL filterinit (nfilter, fn, nband)
   ! Look for input file and create outputfile
   npiglo = getdim (cf_in,cn_x)
   npjglo = getdim (cf_in,cn_y)
   npk    = getdim (cf_in,cn_z, cdtrue=cv_dep, kstatus=ierr)
+  npkf   = npk
   IF ( ierr /= 0 ) THEN
      npk   = getdim (cf_in,'z', cdtrue=cv_dep, kstatus=ierr)
+     npkf  = npk
      IF ( ierr /= 0 ) THEN
         npk   = getdim (cf_in, 'sigma', cdtrue=cv_dep, kstatus=ierr)
+        npkf  = npk
         IF ( ierr /= 0 ) THEN 
            PRINT *,' assume file with no depth'
-           npk=0
+           npk  = 1  ! Data have 1 level...
+           npkf = 0  ! file have no deptht
         ENDIF
      ENDIF
   ENDIF
@@ -178,19 +209,43 @@ PROGRAM cdfsmooth
   ALLOCATE (stypvar(nvars) )
   ALLOCATE (id_var(nvars),ipk(nvars),id_varout(nvars) )
 
+    ALLOCATE ( gdeptmp(npk)  )
+    IF (npkf /= 0 ) THEN 
+       gdeptmp(:) = getvar1d(cf_in, cv_dep, npk )  
+    ELSE
+       gdeptmp(:)=0.  ! dummy value
+    ENDIF
+
   ! get list of variable names and collect attributes in stypvar (optional)
   cv_names(:) = getvarname(cf_in, nvars, stypvar)
 
+  DO jvar=1,nvars
+     ! choose chunk size for output ... not easy not used if lnc4=.false. but anyway ..
+     stypvar(jvar)%ichunk=(/npiglo,MAX(1,npjglo/30),1,1 /)
+  ENDDO
+
   ! ipk gives the number of level or 0 if not a T[Z]YX  variable
   ipk(:)     = getipk (cf_in, nvars, cdep=cv_dep)
   WHERE( ipk == 0 ) cv_names='none'
   stypvar(:)%cname=cv_names
 
+  IF ( ilev /= 0 ) THEN   ! selected level on the command line
+     WHERE (ipk(:) == npk ) ipk = ilev 
+     npk = ilev
+  ELSE                    ! all levels
+     ilev = npk
+     ALLOCATE(iklist(ilev) )
+     iklist(:)=(/ (jk,jk=1,npk) /)
+  ENDIF
+
+  ALLOCATE ( gdep(ilev ) )
+  gdep(:) = (/ (gdeptmp(iklist(jk)), jk=1,ilev) /)
+
   ! create output file taking the sizes in cf_in
   PRINT *, 'Output file name : ', TRIM(cf_out)
-  ncout = create      (cf_out, cf_in,   npiglo, npjglo, npk, cdep=cv_dep)
-  ierr  = createvar   (ncout , stypvar, nvars,  ipk,    id_varout       )
-  ierr  = putheadervar(ncout , cf_in,   npiglo, npjglo, npk, cdep=cv_dep)
+  ncout = create      (cf_out, cf_in,   npiglo, npjglo, npkf, cdep=cv_dep, ld_nc4=lnc4)
+  ierr  = createvar   (ncout , stypvar, nvars,  ipk,    id_varout        , ld_nc4=lnc4)
+  ierr  = putheadervar(ncout , cf_in,   npiglo, npjglo, npkf, pdep=gdep, cdep=cv_dep)
   tim   = getvar1d(cf_in, cv_tim, npt)
   !
   DO jvar = 1,nvars
@@ -202,7 +257,8 @@ PROGRAM cdfsmooth
         DO jt=1,npt
            DO jk=1,ipk(jvar)
               PRINT *, jt,'/',npt,' and ',jk,'/',ipk(jvar)
-              v2d(:,:) = getvar(cf_in,cv_names(jvar),jk,npiglo,npjglo,ktime=jt)
+              ijk = iklist(jk) 
+              v2d(:,:) = getvar(cf_in,cv_names(jvar),ijk,npiglo,npjglo,ktime=jt)
               iw(:,:) = 1
               WHERE ( v2d == rspval ) iw =0
               IF ( ncut /= 0 ) CALL filter( nfilter, v2d, iw, w2d)
diff --git a/cdfspeed.f90 b/src/cdfspeed.f90
similarity index 89%
rename from cdfspeed.f90
rename to src/cdfspeed.f90
index 4d3f30d..fc81823 100644
--- a/cdfspeed.f90
+++ b/src/cdfspeed.f90
@@ -42,13 +42,14 @@ PROGRAM cdfspeed
   TYPE (variable), DIMENSION(1)              :: stypvar              ! structure for attibutes
 
   LOGICAL                                    :: lforcing             ! forcing flag
+  LOGICAL                                    :: lnc4 = .false.       ! flag for netcdf4 chunking and deflation
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
   narg= iargc()
   IF ( narg == 0 ) THEN
      PRINT *,' usage : cdfspeed  U-file V-file U-var V-var [-t T-file] ...'
-     PRINT *,'                  ... [-lev level_list]' 
+     PRINT *,'            ... [-nc4] [-o OUT-file ] [-lev level_list]' 
      PRINT *,'    PURPOSE :'
      PRINT *,'       Computes the speed of ocean currents or wind speed'
      PRINT *,'       '
@@ -65,11 +66,13 @@ PROGRAM cdfspeed
      PRINT *,'       V-var  : netcdf variable name for V component'
      PRINT *,'    '
      PRINT *,'    OPTIONS :'
-     PRINT *,'       [-t T-file ] : indicate any file on gridT for correct header'
+     PRINT *,'       -t T-file  : indicate any file on gridT for correct header'
      PRINT *,'                 of the output file (usefull for 3D files)'
-     PRINT *,'       [-lev level_list ] : indicate a list of levels to be processed'
+     PRINT *,'       -lev level_list  : indicate a list of levels to be processed'
      PRINT *,'                 If not used, all levels are processed.'
      PRINT *,'                 This option should be the last on the command line'
+     PRINT *,'       -nc4 : use netcdf4 output with chunking and deflation'
+     PRINT *,'       -o OUT-file : use specified output file instead of ',TRIM(cf_out)
      PRINT *,'    '
      PRINT *,'    OUTPUT :'
      PRINT *,'       Output on ',TRIM(cf_out),'  variable U '
@@ -90,6 +93,10 @@ PROGRAM cdfspeed
      CASE ( '-t' ) 
        CALL getarg(ijarg, cf_tfil ) ; ijarg = ijarg + 1
        IF ( chkfile (cf_tfil) ) STOP ! missing file
+     CASE ( '-nc4' ) 
+       lnc4=.true.
+     CASE ( '-o' ) 
+       CALL getarg(ijarg, cf_out ) ; ijarg = ijarg + 1
      CASE DEFAULT
        cf_ufil = cldum
        CALL getarg(ijarg, cf_vfil ) ; ijarg = ijarg + 1
@@ -141,6 +148,10 @@ PROGRAM cdfspeed
      nlev = nvpk
   END IF
 
+  ! choose chunk size for output ... not easy not used if lnc4=.false. but
+  ! anyway ..
+  stypvar(1)%ichunk=(/npiglo,MAX(1,npjglo/30),1,1 /)
+
   ! define new variables for output
   stypvar(1)%cname             = 'U'
   stypvar(1)%cunits            = 'm.s-1'
@@ -155,9 +166,9 @@ PROGRAM cdfspeed
   ! create output fileset
   IF (lforcing ) THEN
      ipk(1) = 1 !  2D  no dep variable
-     ncout  = create      (cf_out, cf_vfil, npiglo, npjglo, 0         )
-     ierr   = createvar   (ncout,  stypvar, 1,      ipk,    id_varout )
-     ierr   = putheadervar(ncout,  cf_vfil, npiglo, npjglo, 0         )
+     ncout  = create      (cf_out, cf_vfil, npiglo, npjglo, 0         , ld_nc4=lnc4 )
+     ierr   = createvar   (ncout,  stypvar, 1,      ipk,    id_varout , ld_nc4=lnc4 )
+     ierr   = putheadervar(ncout,  cf_vfil, npiglo, npjglo, 0                       )
      nlev=1 ; nklevel(nlev) = 1
   ELSE
      ALLOCATE ( gdept(nlev), gdeptall(npk) )
@@ -166,9 +177,9 @@ PROGRAM cdfspeed
        gdept(jlev) = gdeptall( nklevel(jlev) )
      END DO
      ipk(1) = nlev
-     ncout  = create      (cf_out, cf_tfil, npiglo, npjglo, nlev              )
-     ierr   = createvar   (ncout,  stypvar, 1,      ipk,    id_varout         )
-     ierr   = putheadervar(ncout,  cf_tfil, npiglo, npjglo, nlev,  pdep=gdept )
+     ncout  = create      (cf_out, cf_tfil, npiglo, npjglo, nlev      , ld_nc4=lnc4   )
+     ierr   = createvar   (ncout,  stypvar, 1,      ipk,    id_varout , ld_nc4=lnc4   )
+     ierr   = putheadervar(ncout,  cf_tfil, npiglo, npjglo, nlev,  pdep=gdept         )
   END IF
 
   ! Allocate arrays
@@ -198,7 +209,7 @@ PROGRAM cdfspeed
            ENDDO
 
            DO ji=1,npiglo 
-             DO jj=npjglo,2 -1
+             DO jj=npjglo,2,-1
                zv(ji,jj) = 0.5*(zv(ji,jj-1)+zv(ji,jj))
              ENDDO
            ENDDO
diff --git a/cdfspice.f90 b/src/cdfspice.f90
similarity index 63%
rename from cdfspice.f90
rename to src/cdfspice.f90
index 92387e2..3971144 100644
--- a/cdfspice.f90
+++ b/src/cdfspice.f90
@@ -20,8 +20,11 @@ PROGRAM cdfspice
   !!
   !! History : 2.1  : 03/2010  : C.O. Dufour  : Original code
   !!           3.0  : 01/2011  : J.M. Molines : Doctor norm + Lic.
+  !!           3.0  : 06/2013  : J.M. Molines : Transfert spice in eos
+  !!                                            Add OMP directive
   !!----------------------------------------------------------------------
   USE cdfio
+  USE eos
   USE modcdfnames
   !!----------------------------------------------------------------------
   !! CDFTOOLS_3.0 , MEOM 2011
@@ -33,34 +36,39 @@ PROGRAM cdfspice
 
   INTEGER(KIND=4)                           :: ji, jj, jk, jt     ! dummy loop index
   INTEGER(KIND=4)                           :: ierr               ! error status
-  INTEGER(KIND=4)                           :: narg, iargc        ! browse command line
+  INTEGER(KIND=4)                           :: narg, ijarg, iargc ! browse command line
   INTEGER(KIND=4)                           :: npiglo, npjglo     ! size of the domain
-  INTEGER(KIND=4)                           :: npk, npt           ! size of the domain
+  INTEGER(KIND=4)                           :: npk, npkk, npt     ! size of the domain
   INTEGER(KIND=4)                           :: ncout              ! ncid of output file
   INTEGER(KIND=4), DIMENSION(1)             :: ipk, id_varout     ! level and  varid's
 
   REAL(KIND=4)                              :: zspval             ! missing value
   REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim                ! time counter
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: ztemp              ! temperature
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zsal               ! salinity
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zmask              ! 2D mask at current level
 
-  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dtemp              ! temperature
   REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dtempt             ! temperature
-  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dsal               ! salinity
   REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dsalt              ! salinity
   REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dsalref            ! reference salinity
   REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dspi               ! spiceness
-  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dmask              ! 2D mask at current level
-  REAL(KIND=8), DIMENSION(6,5)              :: dbet               ! coefficients of spiciness formula
 
   CHARACTER(LEN=256)                        :: cf_tfil            ! input filename
   CHARACTER(LEN=256)                        :: cf_out='spice.nc'  ! output file name
+  CHARACTER(LEN=256)                        :: cldum              ! dummy characte variable variable
+  CHARACTER(LEN=256)                        :: cv_sal             ! salinity name in netcdf
+  CHARACTER(LEN=256)                        :: cv_tem             ! temperature name in netcdf
 
   TYPE (variable), DIMENSION(1)             :: stypvar            ! structure for attributes
+  LOGICAL                                   :: lnc4 = .FALSE.     ! flag for missing files
+
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
   narg = iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfspice T-file '
+     PRINT *,' usage : cdfspice -t T-file [-sal SAL-name] [-tem TEM-name] ...'
+     PRINT *,'        ... [-nc4] [-o OUT-file]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
      PRINT *,'       Compute the spiceness corresponding to temperatures and salinities'
@@ -72,7 +80,14 @@ PROGRAM cdfspice
      PRINT *,'                        s     -> salinity'
      PRINT *,'      '
      PRINT *,'     ARGUMENTS :'
-     PRINT *,'       T-file : netcdf file with temperature and salinity (gridT)' 
+     PRINT *,'       -t T-file : netcdf file with temperature and salinity (gridT)' 
+     PRINT *,'           Single argument T-file can also be used, for backward compatibility'
+     PRINT *,'     '
+     PRINT *,'     OPTIONS :'
+     PRINT *,'       [-sal SAL-name]  : name of salinity variable'
+     PRINT *,'       [-tem TEM-name]  : name of temperature variable'
+     PRINT *,'       [-nc4]  : enable chunking and compression'
+     PRINT *,'       [-o OUT-file]    : specify output filename instead of ',TRIM(cf_out)
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'       none'
@@ -87,13 +102,27 @@ PROGRAM cdfspice
      PRINT *,'             Progress in Oceanography Volume 54, 2002, Pages 493-501.'
      STOP
   ENDIF
-  IF ( narg == 0 ) THEN
-     PRINT *,'usage : cdfspice  gridT '
-     PRINT *,'    Output on spice.nc, variable vospice'
-     STOP
-  ENDIF
 
-  CALL getarg (1, cf_tfil)
+  ijarg=1
+  cv_sal=cn_vosaline
+  cv_tem=cn_votemper
+  DO WHILE ( ijarg <= narg )
+     CALL getarg(ijarg, cldum ) ; ijarg=ijarg+1
+     SELECT CASE ( cldum )
+     CASE ( '-t'   ) ; CALL getarg(ijarg, cf_tfil) ; ijarg=ijarg+1
+     CASE ( '-o'   ) ; CALL getarg(ijarg, cf_out ) ; ijarg=ijarg+1
+     CASE ( '-sal' ) ; CALL getarg(ijarg, cv_sal ) ; ijarg=ijarg+1
+     CASE ( '-tem' ) ; CALL getarg(ijarg, cv_tem ) ; ijarg=ijarg+1
+     CASE ( '-nc4' ) ; lnc4 = .TRUE.
+     CASE DEFAULT
+      IF ( narg == 1 ) THEN
+         cf_tfil = cldum
+      ELSE
+         PRINT *,' option ',TRIM(cldum),' not understood'
+         STOP
+      ENDIF
+     END SELECT
+  ENDDO
 
   IF ( chkfile(cf_tfil) ) STOP ! missing files
 
@@ -102,7 +131,10 @@ PROGRAM cdfspice
   npk    = getdim (cf_tfil,cn_z)
   npt    = getdim (cf_tfil,cn_t)
 
-  ipk(:)                       = npk 
+  npkk=npk
+  IF ( npk == 0 ) npkk=1
+
+  ipk(:)                       = npkk
   stypvar(1)%cname             = 'vospice'
   stypvar(1)%cunits            = 'kg/m3'
   stypvar(1)%rmissing_value    = 0.
@@ -112,61 +144,43 @@ PROGRAM cdfspice
   stypvar(1)%cshort_name       = 'vospice'
   stypvar(1)%conline_operation = 'N/A'
   stypvar(1)%caxis             = 'TZYX'
+  stypvar(1)%ichunk            = (/npiglo, MAX(1,npjglo/30), 1, 1 /)
 
   PRINT *, 'npiglo = ', npiglo
   PRINT *, 'npjglo = ', npjglo
   PRINT *, 'npk    = ', npk
   PRINT *, 'npt    = ', npt
 
-  ALLOCATE (dtemp(npiglo,npjglo), dsal (npiglo,npjglo) )
-  ALLOCATE (dspi( npiglo,npjglo), dmask(npiglo,npjglo) )
+  ALLOCATE (ztemp(npiglo,npjglo), zsal (npiglo,npjglo) )
+  ALLOCATE (dspi( npiglo,npjglo), zmask(npiglo,npjglo) )
   ALLOCATE (dtempt(npiglo,npjglo), dsalt(npiglo,npjglo))
   ALLOCATE (dsalref(npiglo,npjglo))
   ALLOCATE (tim(npt))
 
   ! create output fileset
-  ncout = create      (cf_out, cf_tfil, npiglo, npjglo, npk       )
-  ierr  = createvar   (ncout,  stypvar, 1,      ipk,    id_varout )
+  ncout = create      (cf_out, cf_tfil, npiglo, npjglo, npk,       ld_nc4=lnc4     )
+  ierr  = createvar   (ncout,  stypvar, 1,      ipk,    id_varout, ld_nc4=lnc4     )
   ierr  = putheadervar(ncout,  cf_tfil, npiglo, npjglo, npk       )
 
   tim  = getvar1d(cf_tfil, cn_vtimec, npt     )
   ierr = putvar1d(ncout,   tim,       npt, 'T')
 
-  zspval = getatt(cf_tfil, cn_vosaline, 'missing_value')
-
-  ! Define coefficients to compute spiciness (R*8)
-  dbet(1,1) = 0           ; dbet(1,2) = 7.7442d-01  ; dbet(1,3) = -5.85d-03   ; dbet(1,4) = -9.84d-04   ; dbet(1,5) = -2.06d-04
-  dbet(2,1) = 5.1655d-02  ; dbet(2,2) = 2.034d-03   ; dbet(2,3) = -2.742d-04  ; dbet(2,4) = -8.5d-06    ; dbet(2,5) = 1.36d-05
-  dbet(3,1) = 6.64783d-03 ; dbet(3,2) = -2.4681d-04 ; dbet(3,3) = -1.428d-05  ; dbet(3,4) = 3.337d-05   ; dbet(3,5) = 7.894d-06
-  dbet(4,1) = -5.4023d-05 ; dbet(4,2) = 7.326d-06   ; dbet(4,3) = 7.0036d-06  ; dbet(4,4) = -3.0412d-06 ; dbet(4,5) = -1.0853d-06
-  dbet(5,1) = 3.949d-07   ; dbet(5,2) = -3.029d-08  ; dbet(5,3) = -3.8209d-07 ; dbet(5,4) = 1.0012d-07  ; dbet(5,5) = 4.7133d-08
-  dbet(6,1) = -6.36d-10   ; dbet(6,2) = -1.309d-09  ; dbet(6,3) = 6.048d-09   ; dbet(6,4) = -1.1409d-09 ; dbet(6,5) = -6.676d-10
+  zspval = getspval( cf_tfil, cn_vosaline )
 
   ! Compute spiciness
   DO jt=1,npt
      PRINT *,' TIME = ', jt, tim(jt)/86400.,' days'
-     DO jk = 1, npk
-        dmask(:,:) = 1.
-
-        dtemp(:,:) = getvar(cf_tfil, cn_votemper, jk, npiglo, npjglo, ktime=jt)
-        dsal( :,:) = getvar(cf_tfil, cn_vosaline, jk, npiglo, npjglo, ktime=jt)
-
-        WHERE(dsal == zspval ) dmask = 0
-
-        ! spiciness at time jt, at level jk  
-        dspi(:,:)    = 0.d0
-        dsalref(:,:) = dsal(:,:) - 35.d0
-        dtempt(:,:)  = 1.d0
-        DO ji=1,6
-           dsalt(:,:) = 1.d0
-           DO jj=1,5
-              dspi( :,:) = dspi (:,:) + dbet   (ji,jj) * dtempt(:,:) * dsalt(:,:)
-              dsalt(:,:) = dsalt(:,:) * dsalref( :,: )
-           END DO
-           dtempt(:,:) = dtempt(:,:) * dtemp(:,:)     
-        END DO
-
-        ierr = putvar(ncout, id_varout(1), REAL(dspi*dmask), jk, npiglo, npjglo, ktime=jt)
+     DO jk = 1, npkk
+        PRINT *, 'Level ', jk
+        zmask(:,:) = 1.e0
+
+        ztemp(:,:) = getvar(cf_tfil, cv_tem, jk, npiglo, npjglo, ktime=jt)
+        zsal( :,:) = getvar(cf_tfil, cv_sal, jk, npiglo, npjglo, ktime=jt)
+
+        WHERE(zsal == zspval ) zmask = 0.e0
+     
+        dspi(:,:) = spice ( ztemp, zsal, npiglo, npjglo )
+        ierr      = putvar( ncout, id_varout(1), REAL(dspi*zmask), jk, npiglo, npjglo, ktime=jt)
 
      END DO  ! loop to next level
   END DO  ! next time frame
diff --git a/cdfsstconv.f90 b/src/cdfsstconv.f90
similarity index 100%
rename from cdfsstconv.f90
rename to src/cdfsstconv.f90
diff --git a/cdfstatcoord.f90 b/src/cdfstatcoord.f90
similarity index 100%
rename from cdfstatcoord.f90
rename to src/cdfstatcoord.f90
diff --git a/cdfstats.f90 b/src/cdfstats.f90
similarity index 100%
rename from cdfstats.f90
rename to src/cdfstats.f90
diff --git a/cdfstd.f90 b/src/cdfstd.f90
similarity index 54%
rename from cdfstd.f90
rename to src/cdfstd.f90
index 64bcc98..feeada2 100644
--- a/cdfstd.f90
+++ b/src/cdfstd.f90
@@ -11,6 +11,7 @@ PROGRAM cdfstd
   !!
   !! History : 2.1  : 04/2006  : F. Castruccio : Original code (from cdfmoy)
   !!           3.0  : 01/2011  : J.M. Molines  : Doctor norm + Lic.
+  !!                : 04/2015  : S. Leroux  : add  optstd spval0 options
   !!----------------------------------------------------------------------
   USE cdfio 
   USE modcdfnames
@@ -37,10 +38,14 @@ PROGRAM cdfstd
   INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: id_varoutm          ! varid's of mean var output (optional)
 
   REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: v2d                 ! 2d data array
+  REAL(KIND=4), DIMENSION(:,:),     ALLOCATABLE :: rmask2d             ![from SL]  
   REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: tim                 ! tim counter
   REAL(KIND=4), DIMENSION(1)                    :: timean              ! mean time
+  REAL(KIND=4), DIMENSION(:),       ALLOCATABLE :: zspval_in           ! [from SL]   
 
   REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: dtab, dtab2         ! cumulated values and squared values
+  REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: dtabprev, dtab2prev ! [from SL] keep value from the i-1 timestep
+
   REAL(KIND=8), DIMENSION(:,:),     ALLOCATABLE :: dstd                ! standard deviation
   REAL(KIND=8)                                  :: dtotal_time         ! cumulated time
 
@@ -56,13 +61,16 @@ PROGRAM cdfstd
   TYPE (variable), DIMENSION(:),    ALLOCATABLE :: stypvaro            ! attributes of output variables
 
   LOGICAL                                       :: lcaltmean           ! time mean computation flag
-  LOGICAL                                       :: lsave=.false.       ! mean value save flag
+  LOGICAL                                       :: lsave=.FALSE.       ! mean value save flag
+  LOGICAL                                       :: lspval0=.FALSE.     ! [from SL] flag  if missing values other than zero 
+  LOGICAL                                       :: lnomissincl=.FALSE.  ! [from SL] flag for excluding gridpoints where some values are missing    
+  LOGICAL                                       :: lstdopt=.FALSE.      ! [from SL] flag for using a more optimal algorithm to compute std (and std is unbiased) 
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
   narg= iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfstd list_of files [-save]' 
+     PRINT *,' usage : cdfstd [-save] [-spval0] [-nomissincl] [-stdopt] list_of files ' 
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
      PRINT *,'       Compute the standard deviation of the variables belonging to a set of' 
@@ -74,7 +82,20 @@ PROGRAM cdfstd
      PRINT *,'      '
      PRINT *,'     OPTIONS :'
      PRINT *,'       [ -save ] : Save the mean value of the field, in addition to the '
-     PRINT *,'                   std deviation' 
+     PRINT *,'           std deviation. If used must be appear before list of files.'
+     PRINT *,'       [ -spval0 ] :  set missing_value attribute to 0 for all output'
+     PRINT *,'           variables and take care of the input missing_value.'
+     PRINT *,'           This option is usefull if missing_values differ from files '
+     PRINT *,'           to files.'
+     PRINT *,'           If used it should be called  before the list of input files.'          
+     PRINT *,'       [-nomissincl ] : with this option, the output std and mean are set to'
+     PRINT *,'           missing value at any gridpoint where the variable contains a '
+     PRINT *,'           missing value for at least one timestep. You should combine '
+     PRINT *,'           with -spval0 if missing values are not 0 in all the input files.' 
+     PRINT *,'           If used it should be called  before the list of input files.'              
+     PRINT *,'       [ -stdopt ]:  use a  more optimal algorithm to compute std'
+     PRINT *,'           and std is unbiased.  If used it should be called  before'
+     PRINT*,'            the list of input files.' 
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'       none' 
@@ -89,19 +110,23 @@ PROGRAM cdfstd
      PRINT *,'        cdfmoy, cdfrmsssh, cdfstdevw'
      STOP
   ENDIF
-
   ! look for -save option and one of the file name 
   ijarg = 1
   DO WHILE ( ijarg <= narg ) 
-    CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1
-    SELECT CASE ( cldum )
-    CASE ( '-save' ) 
-      lsave = .true.
-    CASE DEFAULT 
-       cf_in = cldum
-!      CALL getarg (ijarg, cf_in) ; ijarg = ijarg + 1
-       EXIT  ! got the first file
-    END SELECT
+     CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1
+     SELECT CASE ( cldum )
+     CASE ( '-save' ) 
+        lsave = .TRUE.
+     CASE ( '-spval0' )                          ! [from SL]
+        lspval0 = .TRUE.                         ! [from SL]
+     CASE ( '-nomissincl' )                      ! [from SL]
+        lnomissincl = .TRUE.                     ! [from SL]
+     CASE ( '-stdopt' )                          ! [from SL]
+        lstdopt = .TRUE.                         ! [from SL]
+     CASE DEFAULT
+        cf_in = cldum
+        EXIT  ! got the first file
+     END SELECT
   END DO
 
   IF ( chkfile(cf_in) ) STOP ! missing file
@@ -114,10 +139,10 @@ PROGRAM cdfstd
      npk   = getdim (cf_in,'z',kstatus=ierr)
      IF (ierr /= 0 ) THEN
         npk   = getdim (cf_in,'sigma',cdtrue=cv_dep,kstatus=ierr)
-       IF (ierr /= 0 ) THEN
-         PRINT *,' assume file with no depth'
-         npk=0
-       ENDIF
+        IF (ierr /= 0 ) THEN
+           PRINT *,' assume file with no depth'
+           npk=0
+        ENDIF
      ENDIF
   ENDIF
 
@@ -126,7 +151,9 @@ PROGRAM cdfstd
   PRINT *, 'npk    = ', npk
 
   ALLOCATE( dtab(npiglo,npjglo), dtab2(npiglo,npjglo), v2d(npiglo,npjglo) )
+  ALLOCATE( rmask2d(npiglo,npjglo)                                         ) ! [from SL]                                            )
   ALLOCATE( dstd(npiglo,npjglo)                                           )
+  ALLOCATE( dtabprev(npiglo,npjglo), dtab2prev(npiglo,npjglo)             ) ! [from SL]
 
   nvars = getnvar(cf_in)
   PRINT *,' nvars =', nvars
@@ -138,6 +165,12 @@ PROGRAM cdfstd
 
   cv_namesi(:) = getvarname(cf_in, nvars, stypvari)
 
+  IF ( lspval0 ) THEN                              ! [from SL]
+     ALLOCATE ( zspval_in(nvars) )                 ! [from SL]
+     zspval_in(:) = stypvari(:)%rmissing_value     ! [from SL]
+     stypvari(:)%rmissing_value = 0.               ! [from SL]
+  ENDIF                                            ! [from SL]
+
   id_var(:)  = (/(jv, jv=1,nvars)/)
   ipk(:)     = getipk(cf_in, nvars, cdep=cv_dep)
   DO jvar = 1, nvars 
@@ -153,16 +186,18 @@ PROGRAM cdfstd
      stypvaro(jvar)%cshort_name = cv_nameso(jvar)
   END DO
 
+
   ! create output fileset
   ncout = create      (cf_out, cf_in,    npiglo, npjglo, npk, cdep=cv_dep )
   ierr  = createvar   (ncout,  stypvaro, nvars,  ipk,    id_varout        )
   ierr  = putheadervar(ncout,  cf_in,    npiglo, npjglo, npk, cdep=cv_dep )
 
   IF ( lsave )  THEN
-    ! create output fileset for mean values
-    ncou2 = create      (cf_moy, cf_in,    npiglo, npjglo, npk, cdep=cv_dep )
-    ierr  = createvar   (ncou2,  stypvari, nvars,  ipk,    id_varoutm       )
-    ierr  = putheadervar(ncou2,  cf_in,    npiglo, npjglo, npk, cdep=cv_dep )
+     WHERE(ipk == 0 ) stypvari(:)%cname='none'
+     ! create output fileset for mean values
+     ncou2 = create      (cf_moy, cf_in,    npiglo, npjglo, npk, cdep=cv_dep )
+     ierr  = createvar   (ncou2,  stypvari, nvars,  ipk,    id_varoutm       )
+     ierr  = putheadervar(ncou2,  cf_in,    npiglo, npjglo, npk, cdep=cv_dep )
   ENDIF
 
   lcaltmean=.TRUE.
@@ -178,9 +213,24 @@ PROGRAM cdfstd
            PRINT *,'level ',jk
 
            dtab(:,:) = 0.d0; dtab2(:,:) = 0.d0; dtotal_time = 0.d0 
+           dtabprev(:,:) = 0.d0; dtab2prev(:,:) = 0.d0              ! [from SL]
+           rmask2d(:,:) = 1.0                                        ! [from SL]
+
            ntframe = 0
            DO jfil = 1, narg
-              CALL getarg (jfil, cf_in)
+              CALL getarg (jfil, cldum)
+              SELECT CASE (cldum)
+              CASE ( '-save' ) 
+                 CYCLE
+              CASE ( '-spval0' )                                    ! [from SL]
+                 CYCLE
+              CASE ( '-nomissincl' )                                ! [from SL]
+                 CYCLE
+              CASE ( '-stdopt' )                                    ! [from SL]
+                 CYCLE
+              CASE DEFAULT
+                 cf_in=cldum
+              END SELECT
               IF ( chkfile(cf_in) ) STOP ! missing file
 
               IF ( lcaltmean )  THEN
@@ -193,29 +243,57 @@ PROGRAM cdfstd
 
               DO jt=1,npt
                  ntframe = ntframe + 1
-                 v2d(  :,:) = getvar(cf_in, cv_namesi(jvar), jk, npiglo, npjglo, ktime=jt)
-                 dtab( :,:) = dtab( :,:) + v2d(:,:)*1.d0
-                 dtab2(:,:) = dtab2(:,:) + v2d(:,:)*v2d(:,:)*1.d0
+                 v2d(:,:) = getvar(cf_in, cv_namesi(jvar), jk, npiglo, npjglo, ktime=jt)
+                 IF ( lspval0  )  WHERE (v2d == zspval_in(jvar))  v2d = 0.     ! [from SL] change missing values to 0
+                 WHERE (v2d == 0.) rmask2d = 0.                                ! [from SL] keep memory of missing values at gridpoints
+
+
+                 IF (lstdopt) THEN    ! [from SL] New algorithm
+                    IF (ntframe == 1) THEN                                        ! [from SL]
+                       dtab(:,:)  = v2d(:,:)*1.d0                                 ! [from SL]
+                       dtab2(:,:) = 0.d0                                          ! [from SL]
+                       dtabprev(:,:)  = dtab(:,:)                                 ! [from SL]
+                       dtab2prev(:,:) = dtab2(:,:)                                ! [from SL]
+                    ELSE                                      
+                       dtab(:,:)  = dtabprev(:,:)  + (v2d(:,:) -dtabprev(:,:))/ntframe               ! [from SL]           
+                       dtab2(:,:) = dtab2prev(:,:) + ((v2d(:,:)-dtabprev(:,:))*(v2d(:,:)-dtab(:,:))) ! [from SL]   
+                       dtabprev(:,:)  = dtab(:,:)                                 ! [from SL]        
+                       dtab2prev(:,:) = dtab2(:,:)                                ! [from SL]        
+                    ENDIF
+                 ELSE                 ! original algo
+                    dtab( :,:) = dtab( :,:) + v2d(:,:)*1.d0
+                    dtab2(:,:) = dtab2(:,:) + v2d(:,:)*v2d(:,:)*1.d0
+                 ENDIF
+
               END DO
            END DO
 
            ! finish with level jk ; compute mean (assume spval is 0 )
-           dtab( :,:) = dtab( :,:) / ntframe
-           dtab2(:,:) = dtab2(:,:) / ntframe
 
-           WHERE ( dtab2 - dtab*dtab >= 0 ) 
-             dstd = SQRT(dtab2 - dtab*dtab)
-           ELSEWHERE
-             dstd = 0.d0
-           END WHERE
+           IF (lstdopt) THEN                                                          ! [from SL]  if opt "std optimal and unbiased"
+              ! dtab is already normalized with this algo
+              dstd(:,:) = SQRT(dtab2(:,:) / (ntframe-1))                           ! [from SL] unbiased estimate
+
+           ELSE                                                                      ! [from SL]
+              dtab(:,:)  = dtab(:,:) / ntframe                                   
+              dtab2(:,:) = dtab2(:,:) / (ntframe)                       
+              WHERE ( dtab2 - dtab*dtab >= 0 ) 
+                 dstd = SQRT(dtab2 - dtab*dtab)
+              ELSEWHERE
+                 dstd = 0.d0
+              END WHERE
+           ENDIF                                                                     ! [from SL]
+
+           IF ( lnomissincl ) dtab(:,:) = dtab(:,:)*(rmask2d(:,:)*1.d0)           ! [from SL] apply mask 
+           IF ( lnomissincl ) dstd(:,:) = dstd(:,:)*(rmask2d(:,:)*1.d0)           ! [from SL] apply mask 
 
            ! store variable on output file
-                        ierr = putvar(ncout, id_varout(jvar),  REAL(dstd), jk, npiglo, npjglo, kwght=ntframe)
+           ierr = putvar(ncout, id_varout(jvar),  REAL(dstd), jk, npiglo, npjglo, kwght=ntframe)
            IF ( lsave ) ierr = putvar(ncou2, id_varoutm(jvar), REAL(dtab), jk, npiglo, npjglo, kwght=ntframe)
 
            IF ( lcaltmean )  THEN
               timean(1) = dtotal_time / ntframe
-                           ierr = putvar1d(ncout, timean, 1, 'T')
+              ierr = putvar1d(ncout, timean, 1, 'T')
               IF ( lsave ) ierr = putvar1d(ncou2, timean, 1, 'T')
               lcaltmean = .FALSE. ! tmean already computed 
            END IF
@@ -228,3 +306,4 @@ PROGRAM cdfstd
   ierr = closeout(ncou2)
 
 END PROGRAM cdfstd
+
diff --git a/cdfstdevts.f90 b/src/cdfstdevts.f90
similarity index 100%
rename from cdfstdevts.f90
rename to src/cdfstdevts.f90
diff --git a/cdfstdevw.f90 b/src/cdfstdevw.f90
similarity index 77%
rename from cdfstdevw.f90
rename to src/cdfstdevw.f90
index 1deebdf..269f668 100644
--- a/cdfstdevw.f90
+++ b/src/cdfstdevw.f90
@@ -30,6 +30,7 @@ PROGRAM cdfstdevw
 
   REAL(KIND=4), DIMENSION(:,:),  ALLOCATABLE :: zvbar, zvba2      ! mean and mean2 variable
   REAL(KIND=4), DIMENSION(:),    ALLOCATABLE :: tim               ! time counter
+  REAL(KIND=4)                               :: rmiss             ! missing value attribute
 
   REAL(KIND=8), DIMENSION(:,:),  ALLOCATABLE :: dsdev             ! standard deviation
 
@@ -38,37 +39,44 @@ PROGRAM cdfstdevw
   CHARACTER(LEN=256)                         :: cf_out = 'rmsw.nc'! output file name
   CHARACTER(LEN=256)                         :: cv_in, cv_in2     ! input variable names
   CHARACTER(LEN=256)                         :: cldum             ! dummy character variable
+  CHARACTER(LEN=256)                         :: cl_units, cl_longname, cl_shortname
 
   TYPE(variable), DIMENSION(1)               :: stypvaro          ! output data structure
 
   LOGICAL                                    :: lchk = .FALSE.    ! flag for missing files
+  LOGICAL                                    :: lnc4 = .FALSE.    ! flag for netcdf4 with chunking and deflation
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
   cv_in = cn_vovecrtz
 
   narg= iargc()
-  IF ( narg /= 2 ) THEN
-     PRINT *,' usage : cdfstdevw W-file W2-file '
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage : cdfstdevw W-file W2-file [varname] [-o output_file] [-nc4 ]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
-     PRINT *,'       Compute the standard deviation of the vertical velocity'
-     PRINT *,'       from its mean value and its mean square value. '
+     PRINT *,'       Computes the standard deviation of the vertical velocity'
+     PRINT *,'       from its mean value and its mean square value. If a variable name '
+     PRINT *,'       is given, then computes rms of this variable instead of the vertical '
+     PRINT *,'       velocity.'
      PRINT *,'      '
      PRINT *,'       Note that what is computed in this program is stictly the'
      PRINT *,'       standard deviation. It is very often called RMS, which is'
      PRINT *,'       an abuse. It is the same only in the case of zero mean value.'
      PRINT *,'      '
      PRINT *,'     ARGUMENTS :'
-     PRINT *,'       W-file  : netcdf file with mean values for w' 
-     PRINT *,'       W2-file : netcdf file with mean squared values for w' 
+     PRINT *,'       W-file  : netcdf file with mean values for w ( or given variable)' 
+     PRINT *,'       W2-file : netcdf file with mean squared values for w (or given variable)' 
+     PRINT *,'      '
+     PRINT *,'     OPTIONS: '
+     PRINT *,'        varname : give name of variable if not ', TRIM(cn_vovecrtz)
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'       none' 
      PRINT *,'      '
      PRINT *,'     OUTPUT : '
-     PRINT *,'       netcdf file : ', TRIM(cf_out) 
-     PRINT *,'         variables : ', TRIM(cv_in)//'_rms, same unit than the input.'
+     PRINT *,'       netcdf file : ', TRIM(cf_out) ,' (if varname specified, output file is rms_var.nc)'
+     PRINT *,'         variables : ', TRIM(cv_in)//'_rms, (or varname_rms)  same unit than the input.'
      PRINT *,'      '
      PRINT *,'     SEA ALSO :'
      PRINT *,'       cdfstd, cdfrmsssh, cdfstdevts.'
@@ -79,11 +87,14 @@ PROGRAM cdfstdevw
   DO WHILE ( ijarg <= narg) 
      CALL getarg(ijarg, cldum ) ; ijarg=ijarg+1
      SELECT CASE ( cldum )
+     CASE ( '-o'   ) ; CALL getarg(ijarg, cf_out ) ; ijarg=ijarg+1
+     CASE ( '-nc4' ) ; lnc4 = .true.
      CASE DEFAULT
         ireq = ireq + 1
         SELECT CASE ( ireq ) 
         CASE ( 1 ) ; cf_in  = cldum
         CASE ( 2 ) ; cf_in2 = cldum
+        CASE ( 3 ) ; cv_in  = cldum ; cf_out='rms_var.nc'
         CASE DEFAULT
            PRINT *, ' Too many variables ' ; STOP
         END SELECT
@@ -100,13 +111,17 @@ PROGRAM cdfstdevw
   npk    = getdim (cf_in, cn_z)
   npt    = getdim (cf_in, cn_t)
 
+  ierr = getvaratt(cf_in, cv_in, cl_units, rmiss, cl_longname, cl_shortname )
+
+  stypvaro(1)%ichunk = (/ npiglo, MAX(1,npjglo/30), 1,1 /)
+
   ipko(1) = npk
   stypvaro(1)%cname             = TRIM(cv_in)//'_rms'
-  stypvaro(1)%cunits            = 'm/s'
+  stypvaro(1)%cunits            = TRIM(cl_units)
   stypvaro(1)%rmissing_value    = 0.
   stypvaro(1)%valid_min         = 0.
-  stypvaro(1)%valid_max         = 0.01
-  stypvaro(1)%clong_name        = 'RMS_Vertical_Velocity'
+  stypvaro(1)%valid_max         = 10.
+  stypvaro(1)%clong_name        = 'RMS_'//TRIM(cl_longname)
   stypvaro(1)%cshort_name       = TRIM(cv_in)//'_rms'
   stypvaro(1)%conline_operation = 'N/A'
   stypvaro(1)%caxis             = 'TZYX'
@@ -119,8 +134,8 @@ PROGRAM cdfstdevw
   ALLOCATE( zvbar(npiglo,npjglo), zvba2(npiglo,npjglo) )
   ALLOCATE( dsdev(npiglo,npjglo), tim(npt)             )
 
-  ncout = create      (cf_out, cf_in,    npiglo, npjglo, npk       )
-  ierr  = createvar   (ncout,  stypvaro, 1,      ipko,   id_varout )
+  ncout = create      (cf_out, cf_in,    npiglo, npjglo, npk       , ld_nc4=lnc4 )
+  ierr  = createvar   (ncout,  stypvaro, 1,      ipko,   id_varout , ld_nc4=lnc4 )
   ierr  = putheadervar(ncout,  cf_in,    npiglo, npjglo, npk       )
 
   cv_in2 = TRIM(cv_in)//'_sqd'
diff --git a/cdfstrconv.f90 b/src/cdfstrconv.f90
similarity index 100%
rename from cdfstrconv.f90
rename to src/cdfstrconv.f90
diff --git a/cdfsum.f90 b/src/cdfsum.f90
similarity index 50%
rename from cdfsum.f90
rename to src/cdfsum.f90
index 0090212..d490457 100644
--- a/cdfsum.f90
+++ b/src/cdfsum.f90
@@ -30,15 +30,20 @@ PROGRAM cdfsum
   INTEGER(KIND=4)                           :: ijmin=0, ijmax=0    ! domain limitation for computation
   INTEGER(KIND=4)                           :: ikmin=0, ikmax=0    ! domain limitation for computation
   INTEGER(KIND=4)                           :: ierr                ! working integer
-  INTEGER(KIND=4)                           :: narg, iargc         ! command line 
+  INTEGER(KIND=4)                           :: narg, iargc,ijarg   ! command line 
   INTEGER(KIND=4)                           :: npiglo, npjglo      ! size of the domain
-  INTEGER(KIND=4)                           :: npk, npt            ! size of the domain
+  INTEGER(KIND=4)                           :: npk, npkk, npt      ! size of the domain
   INTEGER(KIND=4)                           :: nvpk                ! vertical levels in working variable
   INTEGER(KIND=4)                           :: numout=10           ! logical unit
+  INTEGER(KIND=4)                           :: ncout               ! for netcdf output
+  INTEGER(KIND=4), DIMENSION(2)             :: ipk, id_varout
 
+  REAL(KIND=4)                              :: zspval             ! missing value
   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e1, e2, e3,  zv     ! metrics, velocity
   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zmask               ! npiglo x npjglo
   REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: gdep                ! depth 
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim                 ! time
+  REAL(KIND=4), DIMENSION(1,1)              :: rdummy              ! dummy 2d variable for result
 
   REAL(KIND=8)                              :: dvol, dvol2d        ! volume of the ocean/ layer
   REAL(KIND=8)                              :: dsurf               ! surface of the ocean
@@ -47,48 +52,111 @@ PROGRAM cdfsum
 
   CHARACTER(LEN=256)                        :: cldum               ! dummy string
   CHARACTER(LEN=256)                        :: cf_in               ! file name 
-  CHARACTER(LEN=256)                        :: cv_dep              ! depth name
+  CHARACTER(LEN=256)                        :: cf_out='cdfsum.nc'  ! output file name 
+  CHARACTER(LEN=256)                        :: cv_dep              ! depth name in mesh_zgr
+  CHARACTER(LEN=256)                        :: cdep                ! depth name in output file
   CHARACTER(LEN=256)                        :: cv_in               ! variable name
   CHARACTER(LEN=20)                         :: cv_e1, cv_e2, cv_e3 ! name of the horiz/vert metrics
   CHARACTER(LEN=20)                         :: cv_msk              ! name of mask variable
+  CHARACTER(LEN=20)                         :: cl_vmsk             ! name of external mask variable (-M option)
   CHARACTER(LEN=20)                         :: cvartype            ! variable type
+  CHARACTER(LEN=256)                        :: clunits            ! attribute of output file : units
+  CHARACTER(LEN=256)                        :: cllong_name        !     "      long name
+  CHARACTER(LEN=256)                        :: clshort_name       !     "      short name
+  CHARACTER(LEN=256)                        :: cglobal            !     "      global 
+
+  TYPE(variable), DIMENSION(2)              :: stypvar             ! structure of output
 
   LOGICAL                                   :: lforcing            ! forcing flag
   LOGICAL                                   :: lchk                ! flag for missing files
+  LOGICAL                                   :: lerror=.FALSE.      ! flag for missing arguments
+  LOGICAL                                   :: lfmsk=.FALSE.       ! flag for using non standard mask file
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
   narg= iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfsum IN-file IN-var T| U | V | F | W  ... '
-     PRINT *,'             ... [imin imax jmin jmax kmin kmax] [-full ] '
+     PRINT *,' usage : cdfsum -f IN-file -v IN-var -p T| U | V | F | W  ... '
+     PRINT *,'          ... [-zoom imin imax jmin jmax kmin kmax] [-full ] [-o OUT-file] '
+     PRINT *,'          ... [-M MSK-file VAR-mask ]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
      PRINT *,'       Computes the sum value of the field (3D, weighted)' 
-     PRINT *,'       This sum can be optionally limited to a sub-area.'
+     PRINT *,'       This sum can be optionally limited to a 3D sub-area.'
      PRINT *,'      '
      PRINT *,'     ARGUMENTS :'
-     PRINT *,'       IN-file : netcdf input file.' 
-     PRINT *,'       IN-var  : netcdf variable to work with.'
-     PRINT *,'       T| U | V | F | W : C-grid point where IN-var is located.'
+     PRINT *,'       -f IN-file : netcdf input file.' 
+     PRINT *,'       -v IN-var  : netcdf variable to work with.'
+     PRINT *,'       -p T| U | V | F | W : C-grid point where IN-var is located.'
      PRINT *,'      '
      PRINT *,'     OPTIONS :'
-     PRINT *,'       [imin imax jmin jmax kmin kmax] : limit of the sub area to work with.' 
+     PRINT *,'       [-zoom imin imax jmin jmax kmin kmax] : limit of the 3D sub area. '
      PRINT *,'              if imin=0 all i are taken'
      PRINT *,'              if jmin=0 all j are taken'
      PRINT *,'              if kmin=0 all k are taken'
+     PRINT *,'       [ -full : ] Use full steps instead of default partial steps'
+     PRINT *,'       [-o OUT-file ] : name of the output file instead of', TRIM(cf_out)
+     PRINT *,'       [-M MSK-file VAR-mask] : Allow the use of a non standard mask file '
+     PRINT *,'              with VAR-mask, instead of ',TRIM(cn_fmsk),' and the variable'
+     PRINT *,'              associated with the grid point set by -p argument.'
+     PRINT *,'              This option is a usefull alternative to -zoom option, when the '
+     PRINT *,'              area of interest is not ''box-like'' '
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
-     PRINT *,'      ', TRIM(cn_fhgr),', ',TRIM(cn_fzgr),' and ',TRIM(cn_fmsk) 
+     PRINT *,'      ', TRIM(cn_fhgr),', ',TRIM(cn_fzgr),' and ',TRIM(cn_fmsk),'. If'
+     PRINT *,'         -M option is used, the specified mask file is required instead '
+     PRINT *,'         ', TRIM(cn_fmsk)
      PRINT *,'      '
      PRINT *,'     OUTPUT : '
      PRINT *,'       Standard output.'
+     PRINT *,'       netcdf file : ',TRIM(cf_out),' unless modified with -o option. '
+     PRINT *,'           - 2 variables : vertical profile of sum and 3D sum.'
+     PRINT *,'                         names are sum_<varname> and sum3D_<varname>.'
+     PRINT *,'      '
+     PRINT *,'     SEE ALSO: '
+     PRINT *,'       cdfmean '
      STOP
   ENDIF
 
-  CALL getarg (1, cf_in)
-  CALL getarg (2, cv_in)
-  CALL getarg (3, cvartype)
+  ijarg=1
+  ! mandatory arguments are set to none by default for further check
+  cf_in='none' ; cv_in='none'; cvartype='none'
+  DO WHILE ( ijarg <= narg )
+     CALL getarg( ijarg, cldum) ; ijarg=ijarg+1
+     SELECT CASE (cldum)
+     CASE ( '-f '   ) ; CALL getarg(ijarg, cf_in   ) ; ijarg=ijarg+1
+     CASE ( '-v '   ) ; CALL getarg(ijarg, cv_in   ) ; ijarg=ijarg+1
+     CASE ( '-p '   ) ; CALL getarg(ijarg, cvartype) ; ijarg=ijarg+1
+     CASE ( '-o '   ) ; CALL getarg(ijarg, cf_out  ) ; ijarg=ijarg+1
+     CASE ( '-zoom' ) ; 
+                        CALL getarg(ijarg, cldum   ) ; ijarg=ijarg+1 ; READ(cldum,*)  iimin
+                        CALL getarg(ijarg, cldum   ) ; ijarg=ijarg+1 ; READ(cldum,*)  iimax
+                        CALL getarg(ijarg, cldum   ) ; ijarg=ijarg+1 ; READ(cldum,*)  ijmin
+                        CALL getarg(ijarg, cldum   ) ; ijarg=ijarg+1 ; READ(cldum,*)  ijmax
+                        CALL getarg(ijarg, cldum   ) ; ijarg=ijarg+1 ; READ(cldum,*)  ikmin
+                        CALL getarg(ijarg, cldum   ) ; ijarg=ijarg+1 ; READ(cldum,*)  ikmax
+     CASE ( '-M' ) ;    lfmsk =.TRUE.
+                        CALL getarg(ijarg, cn_fmsk ) ; ijarg=ijarg+1 
+                        CALL getarg(ijarg, cl_vmsk ) ; ijarg=ijarg+1 
+     CASE DEFAULT 
+         PRINT *,' Option ', TRIM(cldum),' not understood ...'
+         STOP
+     END SELECT
+  ENDDO
+  
+  IF ( cf_in == 'none' )  THEN
+     PRINT *,' You must specify an input file with -f option'
+     lerror= lerror .OR. .TRUE. 
+  ENDIF
+  IF ( cv_in == 'none' )  THEN
+     PRINT *,' You must specify an input variable with -v option'
+     lerror= lerror .OR. .TRUE. 
+  ENDIF
+  IF ( cvartype == 'none' )  THEN
+     PRINT *,' You must specify a point type with -p option'
+     lerror= lerror .OR. .TRUE. 
+  ENDIF
+  IF (lerror ) STOP
 
   lchk = chkfile(cn_fhgr)
   lchk = chkfile(cn_fzgr) .OR. lchk
@@ -96,33 +164,19 @@ PROGRAM cdfsum
   lchk = chkfile(cf_in  ) .OR. lchk
   IF ( lchk ) STOP ! missing file
 
-  IF (narg > 3 ) THEN
-     IF ( narg /= 9 ) THEN
-        PRINT *, ' ERROR : You must give 6 optional values (imin imax jmin jmax kmin kmax)'
-        STOP
-     ELSE
-        ! input optional iimin iimax ijmin ijmax
-        CALL getarg ( 4,cldum) ; READ(cldum,*) iimin
-        CALL getarg ( 5,cldum) ; READ(cldum,*) iimax
-        CALL getarg ( 6,cldum) ; READ(cldum,*) ijmin
-        CALL getarg ( 7,cldum) ; READ(cldum,*) ijmax
-        CALL getarg ( 8,cldum) ; READ(cldum,*) ikmin
-        CALL getarg ( 9,cldum) ; READ(cldum,*) ikmax
-     ENDIF
-  ENDIF
-
   npiglo = getdim (cf_in,cn_x)
   npjglo = getdim (cf_in,cn_y)
   npk    = getdim (cf_in,cn_z)
   nvpk   = getvdim(cf_in,cv_in)
   npt    = getdim (cf_in,cn_t)
+  npkk = npk
 
   IF (iimin /= 0 ) THEN ; npiglo = iimax - iimin + 1;  ELSE ; iimin = 1 ;  ENDIF
   IF (ijmin /= 0 ) THEN ; npjglo = ijmax - ijmin + 1;  ELSE ; ijmin = 1 ;  ENDIF
-  IF (ikmin /= 0 ) THEN ; npk    = ikmax - ikmin + 1;  ELSE ; ikmin = 1 ;  ENDIF
+  IF (ikmin /= 0 ) THEN ; npkk   = ikmax - ikmin + 1;  ELSE ; ikmin = 1 ; ikmax = npk ;  ENDIF
 
   IF (nvpk == 2 ) nvpk = 1
-  IF (nvpk == 3 ) nvpk = npk
+  IF (nvpk == 3 ) nvpk = npkk
 
   PRINT *, 'Size of the extracted area :'
   PRINT *, '  npiglo = ', npiglo
@@ -144,7 +198,7 @@ PROGRAM cdfsum
   ALLOCATE ( zmask(npiglo,npjglo) )
   ALLOCATE ( zv   (npiglo,npjglo) )
   ALLOCATE ( e1   (npiglo,npjglo), e2(npiglo,npjglo), e3(npiglo,npjglo) )
-  ALLOCATE ( gdep (npk) )
+  ALLOCATE ( gdep (npk), tim(npt) )
 
   SELECT CASE (TRIM(cvartype))
   CASE ( 'T' )
@@ -153,39 +207,49 @@ PROGRAM cdfsum
      cv_e3  = 'e3t_ps'
      cv_msk = 'tmask'
      cv_dep = cn_gdept
+     cdep   = cn_vdeptht
   CASE ( 'U' )
      cv_e1  = cn_ve1u
      cv_e2  = cn_ve2u
      cv_e3  = 'e3t_ps'
      cv_msk = 'umask'
      cv_dep = cn_gdept
+     cdep   = cn_vdepthu
   CASE ( 'V' )
      cv_e1  = cn_ve1v
      cv_e2  = cn_ve2v
      cv_e3  = 'e3t_ps'
      cv_msk = 'vmask'
      cv_dep = cn_gdept
+     cdep   = cn_vdepthv
   CASE ( 'F' )
      cv_e1  = cn_ve1f
      cv_e2  = cn_ve2f
      cv_e3  = 'e3t_ps'
      cv_msk = 'fmask'
      cv_dep = cn_gdept
+     cdep   = cn_vdeptht
   CASE ( 'W' )
      cv_e1  = cn_ve1t
      cv_e2  = cn_ve2t
      cv_e3  = 'e3w_ps'
      cv_msk = 'tmask'
      cv_dep = cn_gdepw
+     cdep   = cn_vdepthw
   CASE DEFAULT
      PRINT *, 'this type of variable is not known :', TRIM(cvartype)
      STOP
   END SELECT
 
+  ! set cv_mask to on-line specified name if -M option used
+  IF ( lfmsk ) cv_msk = cl_vmsk
+
   e1(:,:) = getvar  (cn_fhgr, cv_e1, 1, npiglo, npjglo, kimin=iimin, kjmin=ijmin)
   e2(:,:) = getvar  (cn_fhgr, cv_e2, 1, npiglo, npjglo, kimin=iimin, kjmin=ijmin)
   gdep(:) = getvare3(cn_fzgr, cv_dep,   npk                                   )
 
+  CALL CreateOutput
+
   dsumt = 0.d0
   DO jt = 1,npt
      dvol = 0.d0
@@ -193,7 +257,7 @@ PROGRAM cdfsum
      zv   = 0.
      DO jk = 1,nvpk
         ik = jk + ikmin -1
-        ! Get velocities v at ik
+        ! Get field  at ik
         zv   (:,:) = getvar(cf_in,   cv_in,  ik, npiglo, npjglo, ktime=jt,   kimin=iimin, kjmin=ijmin)
         zmask(:,:) = getvar(cn_fmsk, cv_msk, ik, npiglo, npjglo,             kimin=iimin, kjmin=ijmin)
         !    zmask(:,npjglo)=0.
@@ -205,12 +269,14 @@ PROGRAM cdfsum
            dsurf  = SUM(DBLE(e1 * e2      * zmask))
            dvol2d = SUM(DBLE(e1 * e2 * e3 * zmask))
            dvol   = dvol + dvol2d
-           dsum2d = SUM(DBLE(zv))
+           dsum2d = SUM(DBLE(zv * e1 * e2 * zmask))
            dsum   = dsum + dsum2d
            IF (dvol2d /= 0 )THEN
               PRINT *, ' Sum value at level ', ik, '(',gdep(ik),' m) ', dsum2d
+              rdummy(1,1)= REAL(dsum2d)
            ELSE
               PRINT *, ' No points in the water at level ', ik, '(',gdep(ik),' m) '
+              rdummy(1,1)= 99999.
            ENDIF
         ELSE
            dsurf  = SUM(DBLE(     e1 * e2 * zmask))
@@ -219,15 +285,65 @@ PROGRAM cdfsum
            PRINT *, ' Sum value at time ',jt,' = ', dsum2d
            PRINT *, '          Surface  = ', dsurf/1.d6,' km^2'
            PRINT *, '       mean value  = ', dsum2d/dsurf
-           WRITE (numout,'(i4," ",1e12.6)') jt, dsum2d
+           WRITE (numout,'(i4," ",1e13.6)') jt, dsum2d
+           rdummy(1,1) = REAL(dsum2d)
         END IF
+        ierr = putvar( ncout, id_varout(1), rdummy, jk, 1,1, ktime=jt)
      END DO
      dsumt = dsumt + dsum
-     IF (.NOT. lforcing) PRINT * ,' Sum value over the ocean: ', dsum
+     IF (.NOT. lforcing) PRINT * ,' Sum value over the ocean: ', dsumt
+     rdummy(1,1) = REAL(dsumt)
+     ierr = putvar( ncout, id_varout(2), rdummy, 1, 1, 1, ktime=jt)
   END DO  ! time loop
   
   PRINT *, ' mean Sum over time ', dsumt/npt
 
   CLOSE(numout)
+  ierr=closeout(ncout)
+
+  CONTAINS
+  SUBROUTINE CreateOutput
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE CreateOutput  ***
+    !!
+    !! ** Purpose : Create netcdf output file  
+    !!----------------------------------------------------------------------
+    REAL(KIND=4), DIMENSION(1,1)              :: zdumlon, zdumlat    ! dummy latitude and longitude
+    !!
+    ! define new variables for output 
+    zdumlon = 0. ; zdumlat = 0.
+    ierr=getvaratt (cf_in, cv_in, clunits, zspval, cllong_name, clshort_name)
+    stypvar%rmissing_value    = 99999.
+    stypvar%valid_min         = -1000.
+    stypvar%valid_max         = 1000.
+    stypvar%scale_factor      = 1.
+    stypvar%add_offset        = 0.
+    stypvar%savelog10         = 0.
+    stypvar%conline_operation = 'N/A'
+
+    ipk(1) = nvpk  ! vertical profile
+    stypvar(1)%cname          = 'sum_'//TRIM(cv_in)
+    stypvar(1)%cunits         = TRIM(clunits)//'.m2'
+    stypvar(1)%clong_name     = 'sum'//TRIM(cllong_name)
+    stypvar(1)%cshort_name    = 'sum'//TRIM(clshort_name)
+    stypvar(1)%caxis          = 'ZT'
+
+    ipk(2) = 1     ! 3D sum
+    stypvar(2)%cname          = 'sum_3D'//TRIM(cv_in)
+    stypvar(2)%cunits         = TRIM(clunits)//'.m3'
+    stypvar(2)%clong_name     = 'sum_3D'//TRIM(cllong_name)
+    stypvar(2)%cshort_name    = 'sum_3D'//TRIM(clshort_name)
+    stypvar(2)%caxis          = 'T'
+
+    ncout = create      (cf_out,     'none',  1,     1  ,   nvpk, cdep=cdep)
+    ierr  = createvar   (ncout,      stypvar, 2    , ipk,   id_varout      )
+    ierr  = putheadervar(ncout,      cf_in,   1,     1, npkk,              &
+                    &  pnavlon=zdumlon, pnavlat=zdumlat,                   &
+                    &  pdep=gdep(ikmin:ikmax),                             &
+                    &  cdep=cdep                                           )
+    tim   = getvar1d(cf_in, cn_vtimec, npt)
+    ierr  = putvar1d(ncout,  tim,      npt, 'T')
+  
+  END SUBROUTINE CreateOutput
 
 END PROGRAM cdfsum
diff --git a/cdftempvol-full.f90 b/src/cdftempvol-full.f90
similarity index 100%
rename from cdftempvol-full.f90
rename to src/cdftempvol-full.f90
diff --git a/src/cdftools-begin.pod b/src/cdftools-begin.pod
new file mode 100644
index 0000000..24fa2b8
--- /dev/null
+++ b/src/cdftools-begin.pod
@@ -0,0 +1,23 @@
+=head1  NAME
+
+CDFTOOLS - diagnostics in Fortran 90 for NEMO model outputs
+
+=head1 PACKAGE DESCRIPTION
+
+C<CDFTOOLS> is a diagnostic package written in fortran 90 for the analysis of NEMO model output, initialized in  the frame of the DRAKKAR project (https://www.drakkar-ocean.eu/). It is now available on GitHub under the CeCILL license (http://www.cecill.info/licences/Licence_CeCILL_V2-en.html).
+
+C<NEMO> web site : http://www.nemo-ocean.eu/
+
+=head1 SYNOPSIS
+
+C<CDFTOOLS> is a collection of fortran program. Each program belonging to this collection is
+designed to perform some specific actions on NEMO output files, and generally provides another netcdf file as output. Output files follow the same CDF format as NEMO file, thus allowing for the building of a secondary data base (assuming that the primary data base is just the raw model output).
+
+This documentation is automatically produced by the concatenation of the C<USAGE> messages produced by each particular program when invoked without any argument. (Standard behaviour of all cdftools). In the documentation, we use a rather classical formalism, where mandatory arguments are just indicated on the command line and options are indicated between squared brackets [..].
+
+Each program name starts with the 3 letters 'cdf' followed by a word related to the action performed by the tools. Example:  C<cdfw  Ufile.nc Vfile.nc > is used to compute the vertical velocity using the horizontal velocity field represented by its two components Ufile.nc and Vfile.nc.
+
+Better than a long speech, the following paragraphs  describes each of the existing cdftools.
+
+=head1 COMMANDS DESCRIPTION
+
diff --git a/cdftools-end.pod b/src/cdftools-end.pod
similarity index 82%
rename from cdftools-end.pod
rename to src/cdftools-end.pod
index c73d95a..5968d57 100644
--- a/cdftools-end.pod
+++ b/src/cdftools-end.pod
@@ -1,15 +1,7 @@
 
-=head1 AUTHORS
-
-Written by Jean-Marc Molines, Grenoble - France
-
-Contributors : F. Castruccio, C. Dufour, R. Dussin, M. Juza, 
-A. Lecointre, P. Mathiot, A. Melet., A.M. Treguier
-
 =head1 LICENSE AND COPYRIGHT
 
-Copyright (C) 1998-2012 LEGI / Team MEOM / CNRS UMR 5518 - Grenoble - France,
-Jean-Marc.Molines at legi.grenoble-inp.fr
+Copyright (C) 1998-2016 IGE-MEOM (Jean-Marc.Molines at univ-grenoble-alpes.fr )
 
 This software is governed by the CeCILL  license under French law and
 abiding by the rules of distribution of free software.  You can  use, 
diff --git a/cdftools.f90 b/src/cdftools.f90
similarity index 50%
rename from cdftools.f90
rename to src/cdftools.f90
index 634cf57..5b2cc61 100644
--- a/cdftools.f90
+++ b/src/cdftools.f90
@@ -21,8 +21,11 @@ MODULE cdftools
   PRIVATE     
   ! list of public subroutines that can be called
   PUBLIC  :: cdf_findij 
+  PUBLIC  :: broken_line
+
   PRIVATE :: NearestPoint
   PRIVATE :: dist 
+  PRIVATE :: interm_pt
 
   !!----------------------------------------------------------------------
   !! CDFTOOLS_3.0 , MEOM 2011
@@ -33,8 +36,9 @@ MODULE cdftools
 
 CONTAINS
 
-  SUBROUTINE cdf_findij ( pxmin, pxmax, pymin, pymax,           &
-       &         kimin, kimax, kjmin, kjmax, cd_coord, cd_point, cd_verbose)
+  SUBROUTINE cdf_findij ( pxmin, pxmax, pymin, pymax,                        &
+       &         kimin, kimax, kjmin, kjmax, cd_coord, cd_point, cd_verbose ,&
+       &         plonmin, plonmax, platmin, platmax )
     !!---------------------------------------------------------------------
     !!                  ***  ROUTINE cdf_findij  ***
     !!
@@ -46,19 +50,21 @@ CONTAINS
     CHARACTER(*), OPTIONAL,        INTENT(in) :: cd_coord                   !: coordinate file name (D: cn_fcoo)
     CHARACTER(*), OPTIONAL,        INTENT(in) :: cd_point                   !: point type           (D: F )
     CHARACTER(*), OPTIONAL,        INTENT(in) :: cd_verbose                 !: verbose flag         (D: N ) Y
+    REAL(KIND=4), OPTIONAL,       INTENT(out) :: plonmin, plonmax           !: model lonmn, lonmax
+    REAL(KIND=4), OPTIONAL,       INTENT(out) :: platmin, platmax           !: model  latmin, latmax
 
     INTEGER(KIND=4)                           :: initer
     INTEGER(KIND=4)                           :: imin, imax, jmin, jmax
     INTEGER(KIND=4), SAVE                     :: iloc, jloc
-    INTEGER(KIND=4)                           :: ipiglo, ipjglo
+    INTEGER(KIND=4), SAVE                     :: ipiglo, ipjglo
     INTEGER(KIND=4), PARAMETER                :: jp_itermax=15
-  
+
     REAL(KIND=8)                              :: dl_xmin, dl_xmax, dl_ymin, dl_ymax
     REAL(KIND=8)                              :: dl_dis
     REAL(KIND=8)                              :: dl_glam0, dl_emax
-    REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dl_glam, dl_gphi, dl_e1, dl_e2
+    REAL(KIND=8), SAVE, DIMENSION(:,:), ALLOCATABLE :: dl_glam, dl_gphi, dl_e1, dl_e2
 
-    REAL(KIND=4)                              :: zglamfound, zglamin, zglamax
+    REAL(KIND=4)                              :: zglamfound, zglamin, zglamax, zgphmin, zgphmax
 
     CHARACTER(LEN=256)                        :: cl_type='F'
     CHARACTER(LEN=256)                        :: clcoo
@@ -66,18 +72,23 @@ CONTAINS
     LOGICAL                                   :: ll_again, ll_bnd, ll_verbose=.false.
     !!--------------------------------------------------------------------------
     CALL ReadCdfNames()
+    imin = 0 ; jmin = 0
 
     dl_xmin = pxmin
     dl_xmax = pxmax
     dl_ymin = pymin
     dl_ymax = pymax
 
-    IF ( PRESENT( cd_coord)  ) clcoo=cd_coord
-    IF ( PRESENT( cd_point)  ) cl_type=cd_point
+    clcoo = cn_fhgr
+
+    IF ( PRESENT( cd_coord)  ) clcoo  = cd_coord
+    IF ( PRESENT( cd_point)  ) cl_type= cd_point
     IF ( PRESENT( cd_verbose))   THEN
-      IF ( cd_verbose(1:1) == 'Y' .OR. cd_verbose(1:1) == 'y' ) ll_verbose=.true.
+       IF ( cd_verbose(1:1) == 'Y' .OR. cd_verbose(1:1) == 'y' ) ll_verbose=.true.
     ENDIF
 
+    IF ( .NOT. ALLOCATED (dl_glam) ) THEN 
+
     IF (chkfile (clcoo) ) STOP ! missing file
 
     ipiglo= getdim (clcoo, cn_x)
@@ -123,11 +134,13 @@ CONTAINS
 
     IF (dl_xmin < dl_glam0) dl_xmin = dl_xmin + 360.d0
     IF (dl_xmax < dl_glam0) dl_xmax = dl_xmax + 360.d0
+    ENDIF  ! 
 
 
     ! deal with xmin, ymin
     ll_again = .TRUE.
     initer = 1
+    iloc=ipiglo/2 ; jloc=ipjglo/2
 
     DO WHILE (ll_again)
        CALL NearestPoint(dl_xmin, dl_ymin, ipiglo, ipjglo, dl_glam, dl_gphi, iloc, jloc, ll_bnd)
@@ -141,19 +154,19 @@ CONTAINS
        IF (dl_dis  > dl_emax ) THEN
           zglamfound = dl_glam(iloc,jloc) ; IF (zglamfound > 180.)  zglamfound=zglamfound - 360.
 
-          PRINT 9000, 'Long= ',zglamfound,' Lat = ',dl_gphi(iloc,jloc) , iloc, jloc 
-          PRINT *,' Algorithm does''nt converge ', dl_dis
+!         PRINT 9000, 'Long= ',zglamfound,' Lat = ',dl_gphi(iloc,jloc) , iloc, jloc 
+!         PRINT *,' Algorithm does''nt converge ', dl_dis
 
           IF ( initer >= jp_itermax ) THEN
-            PRINT *, ' no convergence after ', jp_itermax,' iterations'
-            iloc     = -1000
-            jloc     = -1000
-            ll_again = .FALSE.
+!            PRINT *, ' no convergence after ', jp_itermax,' iterations'
+             iloc     = -1000
+             jloc     = -1000
+             ll_again = .FALSE.
           ELSE
-            ll_again = .TRUE.
-            initer   = initer +1
-            jloc     = (initer -1)* ipjglo/initer
-            iloc     = (initer -1)* ipiglo/jp_itermax
+             ll_again = .TRUE.
+             initer   = initer +1
+             jloc     = (initer -1)* ipjglo/initer
+             iloc     = (initer -1)* ipiglo/jp_itermax
           ENDIF
        ELSE
           IF ( ll_verbose ) THEN
@@ -163,8 +176,8 @@ CONTAINS
        END IF
     END DO
 
-    IF (ll_bnd .AND. ll_verbose ) THEN
-       WRITE (*,*)'Point  Out of domain or on boundary'
+    IF (ll_bnd ) THEN
+       IF (ll_verbose) WRITE (*,*)'Point  Out of domain or on boundary'
     ELSE
        imin=iloc
        jmin=jloc
@@ -172,64 +185,75 @@ CONTAINS
 
     ! deal with xmax, ymax
     IF (  pxmin == pxmax .AND. pymin == pymax ) THEN
-      ! job already done with first point
-      imax=imin
-      jmax=jmin
+       ! job already done with first point
+       imax=imin
+       jmax=jmin
     ELSE
-    ll_again = .TRUE.
-    initer = 1
-    iloc=ipiglo/2 ; jloc=ipjglo/2
-
-    DO WHILE (ll_again)
-       CALL NearestPoint(dl_xmax, dl_ymax, ipiglo, ipjglo, dl_glam, dl_gphi, iloc, jloc, ll_bnd)
-
-       ! distance between the target point and the nearest point
-       dl_dis = dist(dl_xmax, dl_glam(iloc,jloc), dl_ymax, dl_gphi(iloc,jloc) ) ! in km
-
-       ! typical grid size (diagonal) in the vicinity of nearest point
-       dl_emax = MAX(dl_e1(iloc,jloc),dl_e2(iloc,jloc))/1000.*SQRT(2.) ! in km
-
-       IF (dl_dis >  dl_emax ) THEN
-          zglamfound=dl_glam(iloc,jloc) ; IF (zglamfound > 180.)  zglamfound=zglamfound -360.
-
-          PRINT 9000, 'Long= ',zglamfound,' Lat = ',dl_gphi(iloc,jloc), iloc, jloc
-          PRINT *,' Algorithm does''nt converge ', dl_dis
-
-          IF ( initer >= jp_itermax ) THEN
-            PRINT *, ' no convergence after ', jp_itermax,' iterations'
-            iloc     = -1000
-            jloc     = -1000
-            ll_again = .FALSE.
+       ll_again = .TRUE.
+       initer = 1
+       iloc=ipiglo/2 ; jloc=ipjglo/2
+
+       DO WHILE (ll_again)
+          CALL NearestPoint(dl_xmax, dl_ymax, ipiglo, ipjglo, dl_glam, dl_gphi, iloc, jloc, ll_bnd)
+
+          ! distance between the target point and the nearest point
+          dl_dis = dist(dl_xmax, dl_glam(iloc,jloc), dl_ymax, dl_gphi(iloc,jloc) ) ! in km
+
+          ! typical grid size (diagonal) in the vicinity of nearest point
+          dl_emax = MAX(dl_e1(iloc,jloc),dl_e2(iloc,jloc))/1000.*SQRT(2.) ! in km
+
+          IF (dl_dis >  dl_emax ) THEN
+             zglamfound=dl_glam(iloc,jloc) ; IF (zglamfound > 180.)  zglamfound=zglamfound -360.
+
+!            PRINT 9000, 'Long= ',zglamfound,' Lat = ',dl_gphi(iloc,jloc), iloc, jloc
+!            PRINT *,' Algorithm does''nt converge ', dl_dis
+
+             IF ( initer >= jp_itermax ) THEN
+!               PRINT *, ' no convergence after ', jp_itermax,' iterations'
+                iloc     = -1000
+                jloc     = -1000
+                ll_again = .FALSE.
+             ELSE
+                ll_again = .TRUE.
+                initer   = initer +1
+                jloc     = (initer -1)* ipjglo/initer
+                iloc     = (initer -1)* ipiglo/jp_itermax
+             ENDIF
           ELSE
-            ll_again = .TRUE.
-            initer   = initer +1
-            jloc     = (initer -1)* ipjglo/initer
-            iloc     = (initer -1)* ipiglo/jp_itermax
-          ENDIF
+             IF ( ll_verbose ) THEN
+                PRINT '("#  dl_dis= ",f8.3," km")', dl_dis
+             ENDIF
+             ll_again = .FALSE.
+          END IF
+       END DO
+       IF (ll_bnd ) THEN
+          IF (ll_verbose) WRITE (*,*) 'Point  Out of domain or on boundary'
        ELSE
-          IF ( ll_verbose ) THEN
-             PRINT '("#  dl_dis= ",f8.3," km")', dl_dis
-          ENDIF
-          ll_again = .FALSE.
-       END IF
-    END DO
-    IF (ll_bnd .AND. ll_verbose ) THEN
-       WRITE (*,*) 'Point  Out of domain or on boundary'
-    ELSE
-       imax=iloc
-       jmax=jloc
-    ENDIF
+          imax=iloc
+          jmax=jloc
+       ENDIF
     ENDIF
 
     IF (ll_verbose) PRINT 9001, imin, imax, jmin, jmax
 
     kimin   = imin ; kimax = imax ; kjmin   = jmin ; kjmax = jmax
+   IF ( ll_bnd .OR. imin < 0 ) THEN
+     zglamin= -9999. ; zglamax = -9999
+     zgphmin= -9999. ; zgphmax = -9999
+   ELSE
     zglamin = dl_glam(imin,jmin)  ; zglamax = dl_glam(imax,jmax)
+    zgphmin = dl_gphi(imin,jmin)  ; zgphmax = dl_gphi(imax,jmax)
+   ENDIF
 
     IF ( zglamin > 180 ) zglamin=zglamin-360.
     IF ( zglamax > 180 ) zglamax=zglamax-360.
 
-    IF ( ll_verbose) PRINT 9002, zglamin, zglamax, dl_gphi(imin,jmin),dl_gphi(imax,jmax)
+    IF ( ll_verbose) PRINT 9002, zglamin, zglamax, zgphmin, zgphmax
+
+    IF ( PRESENT (plonmin) ) plonmin=zglamin
+    IF ( PRESENT (plonmax) ) plonmax=zglamax
+    IF ( PRESENT (platmin) ) platmin=zgphmin
+    IF ( PRESENT (platmax) ) platmax=zgphmax
 
 9000 FORMAT(a,f8.2,a,f8.2,2i5)
 9001 FORMAT(4i10)
@@ -237,7 +261,156 @@ CONTAINS
 
   END SUBROUTINE cdf_findij
 
+  SUBROUTINE  broken_line( kimin, kimax, kjmin, kjmax, & 
+       &                     pxx, pyy, knn , kpi, kpj, knormu, knormv)
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE broken_line  ***
+    !!
+    !! ** Purpose :  determine the broken line between 2 points 
+    !!
+    !! ** Method  :  Compute the equation of the strait line joining
+    !!               the 2 points, on the model I,J domain. Compute
+    !!               both y(x) and x(y) and work with the minimum sloping
+    !!               line. 
+    !!
+    !!----------------------------------------------------------------------
+    INTEGER(KIND=4),            INTENT(in ) :: kimin, kimax, kjmin, kjmax
+    INTEGER(KIND=4),            INTENT(out) :: knn
+    INTEGER(KIND=4),            INTENT(in ) :: kpi, kpj
+    INTEGER(KIND=4),            INTENT(out) :: knormu, knormv
+    REAL(KIND=4), DIMENSION(kpi+kpj), INTENT(out) :: pxx, pyy
+
+    INTEGER(KIND=4) :: ji, jj, jk   ! dummy loop index
+    INTEGER(KIND=4) :: ii0, ij0, ii1, ij1, iitmp, ijtmp
+    INTEGER(KIND=4) :: iist, ijst
+    INTEGER(KIND=4) :: ii, ij
+    INTEGER(KIND=4) :: idirx, idiry
+    INTEGER(KIND=4) :: ipts
+
+    REAL(KIND=4)    :: zxi0, zyj0, zxi1, zyj1
+    REAL(KIND=4)    :: zai, zbi
+    REAL(KIND=4)    :: zaj, zbj
+    REAL(KIND=4)    :: zd
+
+    COMPLEX, DIMENSION(kpi+kpj) :: ylpt           ! array of points coordinates in a section
+    COMPLEX                     :: ylpti          ! working point
+    !!----------------------------------------------------------------------
+
+    !! Find the broken line between P1 (kimin,kjmin) and P2 (kimax, kjmax)
+    ! ... Initialization
+    ii0  = kimin ; ij0  = kjmin ; ii1  = kimax ;  ij1 = kjmax
+    zxi0 = ii0   ; zyj0 = ij0   ; zxi1 = ii1   ; zyj1 = ij1
+
+    ! compute direction of integrations and signs
+    !The transport across the section is the dot product of
+    !integral(line){(Mx,My)*dS}
+    !Mx=integral(u*dz)  My=integral(v*dz)) and dS=(dy,-dx)}
+
+    !By defining the direction of the integration as
+    idirx = SIGN(1,ii1-ii0) !positive to the east or if ii1=ii0
+    idiry = SIGN(1,ij1-ij0) !positive to the north or if ij1=ij0
+
+    !Then dS=(e2u*idiry,-e1v*idirx)
+    !This will produce the following sign convention:
+    !    West-to-est line (dx>0, dy=0)=> -My*dx (-ve for a northward flow)
+    !    South-to-north   (dy>0, dx=0)=>  Mx*dy (+ve for an eastward flow)
+    knormu =  idiry
+    knormv = -idirx
+
+    ! .. Compute equation:  ryj = zaj rxi + zbj [valid in the (i,j) plane]
+    IF ( (zxi1 -zxi0) /=  0 ) THEN
+       zaj = (zyj1 - zyj0 ) / (zxi1 -zxi0)
+       zbj = zyj0 - zaj * zxi0
+    ELSE
+       zaj = 10000.  ! flag value
+       zbj = 0.
+    END IF
+    ! .. Compute equation:  rxi = zai ryj + zbi [valid in the (i,j) plane]
+    IF ( (zyj1 -zyj0) /=  0 ) THEN
+       zai = (zxi1 - zxi0 ) / ( zyj1 -zyj0 )
+       zbi = zxi0 - zai * zyj0
+    ELSE
+       zai = 10000. ! flag value
+       zbi = 0.
+    END IF
+
+    ! ..  Compute the integer pathway: a succession of F points
+    ipts=0
+    ! .. Chose the strait line with the smallest slope
+    IF (ABS(zaj) <=  1 ) THEN
+       ! ... Here, the best line is y(x)
+       ! ... If ii1 < ii0 swap points [ always describe section from left to right ]
+       IF (ii1 <  ii0 ) THEN
+          iitmp = ii0   ; ijtmp = ij0
+          ii0   = ii1   ; ij0   = ij1
+          ii1   = iitmp ; ij1   = ijtmp
+       END IF
+
+       ! iist,ijst is the grid offset to pass from F point to either U/V point
+       IF ( ij1 >= ij0 ) THEN     ! line heading NE
+          iist = 1 ; ijst = 1
+       ELSE                       ! line heading SE
+          iist = 1 ; ijst = 0
+       END IF
+
+       ! ... compute the nearest ji point on the line crossing at ji
+       DO ji=ii0, ii1
+          ipts=ipts+1
+          IF (ipts > kpi+kpj) STOP 'ipts > kpi+kpj !'
+          ij=NINT(zaj*ji + zbj )
+          ylpt(ipts) = CMPLX(ji,ij)
+       END DO
+    ELSE
+       ! ... Here, the best line is x(y)
+       ! ... If ij1 < ij0 swap points [ always describe section from bottom to top ]
+       IF (ij1 <  ij0 ) THEN
+          iitmp = ii0   ; ijtmp = ij0
+          ii0   = ii1   ; ij0   = ij1
+          ii1   = iitmp ; ij1   = ijtmp
+       END IF
+
+       ! iist,ijst is the grid offset to pass from F point to either U/V point
+       IF ( ii1 >=  ii0 ) THEN
+          iist = 1 ; ijst = 1
+       ELSE
+          iist = 0 ; ijst = 1
+       END IF
+
+       ! ... compute the nearest ji point on the line crossing at jj
+       DO jj=ij0,ij1
+          ipts=ipts+1
+          IF (ipts > kpi+kpj) STOP 'ipts > kpi+kpj !'
+          ii=NINT(zai*jj + zbi)
+          ylpt(ipts) = CMPLX(ii,jj)
+       END DO
+    END IF
+    !!
+    !! Look for intermediate points to be added.
+    !  ..  The final positions are saved in pxx,pyy
+    pxx(1) = REAL(ylpt(1))
+    pyy(1) = IMAG(ylpt(1))
+    knn     = 1
+
+    DO jk=2,ipts
+       ! .. distance between 2 neighbour points
+       zd=ABS(ylpt(jk)-ylpt(jk-1))
+       ! .. intermediate points required if zd > 1
+       IF ( zd > 1 ) THEN
+          CALL interm_pt(ylpt, jk, zai, zbi, zaj, zbj, ylpti)
+          knn=knn+1
+          IF (knn > kpi+kpj) STOP 'knn>kpi+kpj !'
+          pxx(knn) = REAL(ylpti)
+          pyy(knn) = IMAG(ylpti)
+       END IF
+       knn=knn+1
+       IF (knn > kpi+kpj) STOP 'knn>kpi+kpj !'
+       pxx(knn) = REAL(ylpt(jk))
+       pyy(knn) = IMAG(ylpt(jk))
+    END DO
 
+  END SUBROUTINE broken_line
+
+! Private subroutines and functions
   SUBROUTINE NearestPoint(ddlon, ddlat, kpi, kpj, ddlam, ddphi, kpiloc, kpjloc, ld_bnd)
     !!---------------------------------------------------------------------
     !!                  ***  ROUTINE NearestPoint  ***
@@ -254,9 +427,9 @@ CONTAINS
     !! References : P.A. Darbon and A. de Miranda acknowledged for this 
     !!              clever algorithm developped in CLIPPER.
     !!----------------------------------------------------------------------
-    REAL(KIND=8),                     INTENT(in) :: ddlon, ddlat        !: lon and lat of target point
+    REAL(KIND=8),                     INTENT(in) :: ddlon, ddlat      !: lon and lat of target point
     INTEGER(KIND=4),                 INTENT (in) :: kpi, kpj          !: grid size
-    REAL(KIND=8), DIMENSION(kpi,kpj), INTENT(in) :: ddlam, ddphi        !: model grid layout
+    REAL(KIND=8), DIMENSION(kpi,kpj), INTENT(in) :: ddlam, ddphi      !: model grid layout
     INTEGER(KIND=4),              INTENT (inout) :: kpiloc, kpjloc    !: nearest point location
     LOGICAL                                      :: ld_bnd            !: reach boundary flag
 
@@ -313,7 +486,7 @@ CONTAINS
        IF (kpjloc == 2  .OR. kpjloc ==kpj-1) ld_bnd=.TRUE.
     END DO
 
-  END SUBROUTINE  NEARESTPOINT
+  END SUBROUTINE  NearestPoint
 
 
   REAL(KIND=8) FUNCTION dist(ddlona, ddlonb, ddlata, ddlatb)
@@ -376,4 +549,101 @@ CONTAINS
 
   END FUNCTION dist
 
+
+  SUBROUTINE interm_pt (ydpt, kk, pai, pbi, paj, pbj, ydpti)
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE nterm_pt  ***
+    !!
+    !! ** Purpose : Find the best intermediate points on a pathway.
+    !!
+    !! ** Method  : ydpt : complex vector of the positions of the nearest points
+    !!               kk  : current working index
+    !!          pai, pbi : slope and original ordinate of x(y)
+    !!          paj, pbj : slope and original ordinate of y(x)
+    !!             ydpti : Complex holding the position of intermediate point 
+    !!
+    !! ** Reference : 19/07/1999 : J.M. Molines in Clipper
+    !!----------------------------------------------------------------------
+    COMPLEX, DIMENSION(:), INTENT(in ) :: ydpt
+    COMPLEX,               INTENT(out) :: ydpti
+    REAL(KIND=4),          INTENT(in ) :: pai, pbi, paj, pbj
+    INTEGER(KIND=4),       INTENT(in ) :: kk
+    ! ... local
+    COMPLEX                            :: ylptmp1, ylptmp2
+    REAL(KIND=4)                       :: za0, zb0
+    REAL(KIND=4)                       :: za1, zb1
+    REAL(KIND=4)                       :: zd1, zd2
+    REAL(KIND=4)                       :: zxm, zym
+    REAL(KIND=4)                       :: zxp, zyp
+    !!----------------------------------------------------------------------
+    ! ... Determines whether we use y(x) or x(y):
+    IF (ABS(paj) <=  1) THEN
+       ! .....  use y(x)
+       ! ... possible intermediate points:
+       ylptmp1=ydpt(kk-1)+(1.,0.)                 ! M1 
+       ylptmp2=ydpt(kk-1)+CMPLX(0.,SIGN(1.,paj))  ! M2
+       !
+       ! ... M1 is the candidate point:
+       zxm=REAL(ylptmp1)
+       zym=IMAG(ylptmp1)
+       za0=paj
+       zb0=pbj
+       !
+       za1=-1./za0
+       zb1=zym - za1*zxm
+       ! ... P1 is the projection of M1 on the strait line
+       zxp=-(zb1-zb0)/(za1-za0)
+       zyp=za0*zxp + zb0
+       ! ... zd1 is the distance M1P1
+       zd1=(zxm-zxp)*(zxm-zxp) + (zym-zyp)*(zym-zyp)
+       !
+       ! ... M2 is the candidate point:
+       zxm=REAL(ylptmp2)
+       zym=IMAG(ylptmp2)
+       za1=-1./za0
+       zb1=zym - za1*zxm
+       ! ... P2 is the projection of M2 on the strait line
+       zxp=-(zb1-zb0)/(za1-za0)
+       zyp=za0*zxp + zb0
+       ! ... zd2 is the distance M2P2
+       zd2=(zxm-zxp)*(zxm-zxp) + (zym-zyp)*(zym-zyp)
+       ! ... chose the smallest (zd1,zd2)
+       IF (zd2 <=  zd1) THEN
+          ydpti=ylptmp2   ! use M2
+       ELSE
+          ydpti=ylptmp1   ! use M1
+       END IF
+       !
+    ELSE   
+       ! ...  use x(y)
+       ! ... possible intermediate points:
+       ylptmp1=ydpt(kk-1)+CMPLX(SIGN(1.,pai),0.)  ! M1
+       ylptmp2=ydpt(kk-1)+(0.,1.)                 ! M2
+       ! 
+       ! ... M1 is the candidate point:
+       zxm=REAL(ylptmp1)
+       zym=IMAG(ylptmp1)
+       za0=pai
+       zb0=pbi
+       !
+       za1=-1./za0
+       zb1=zxm - za1*zym
+       zyp=-(zb1-zb0)/(za1-za0)
+       zxp=za0*zyp + zb0
+       zd1=(zxm-zxp)*(zxm-zxp) + (zym-zyp)*(zym-zyp)
+       !
+       zxm=REAL(ylptmp2)
+       zym=IMAG(ylptmp2)
+       za1=-1./za0
+       zb1=zxm - za1*zym
+       zyp=-(zb1-zb0)/(za1-za0)
+       zxp=za0*zyp + zb0
+       zd2=(zxm-zxp)*(zxm-zxp) + (zym-zyp)*(zym-zyp)
+       IF (zd2 <=  zd1) THEN
+          ydpti=ylptmp2
+       ELSE
+          ydpti=ylptmp1
+       END IF
+    END IF
+  END SUBROUTINE interm_pt
 END MODULE cdftools
diff --git a/cdftransig_xy3d.f90 b/src/cdftransig_xy3d.f90
similarity index 100%
rename from cdftransig_xy3d.f90
rename to src/cdftransig_xy3d.f90
diff --git a/src/cdftransport.f90 b/src/cdftransport.f90
new file mode 100644
index 0000000..cd9424f
--- /dev/null
+++ b/src/cdftransport.f90
@@ -0,0 +1,1245 @@
+PROGRAM cdftransport
+   !!======================================================================
+   !!                     ***  PROGRAM  cdftransport  ***
+   !!=====================================================================
+   !!  ** Purpose : Compute Transports across a section. 
+   !!               By default, mass (Sv) and  heat(PW)/salt(kT/s) transports
+   !!               are computed unless -noheat option is used (mass 
+   !!               transport only).
+   !!
+   !!  ** Method  : The begining and end point of the section are given in 
+   !!               term of F-points index. A broken line joining successive
+   !!               F-points is defined between the begining and end point
+   !!               of the section. Therefore each segment between F-points
+   !!               is either a zonal or meridional segment corresponding to
+   !!               V or U velocity component. Doing so, the volume conservation
+   !!               is ensured as velocities are not interpolated, and stay 
+   !!               on the native model grid. 
+   !!                 The section name and the begin/end point of a section are
+   !!               read from standard input, till 'EOF' is given as section
+   !!               name. This make possible to give a bunch of sections in 
+   !!               an ASCII files and use the < redirection.
+   !!            SIGN CONVENTION : The transport is positive when the flow cross
+   !!               the section to the right, negative otherwise. This depends
+   !!               on the sense the section is described.  With this convention
+   !!               The algebric sum of transports accross sections forming a 
+   !!               closed area is 0. 
+   !!            OPTIONS :
+   !!               -full   : full step case
+   !!               -noheat : only mass transport is computed.
+   !!               -time   : specify the time frame to be used
+   !!               -zlimit : transports can be computed in different depth layers
+   !!                         defined by their depth limit
+   !!            REQUIREMENT :
+   !!               mesh-mask file are required in the current directory.
+   !!            
+   !!
+   !! History : 2.1  : 01/2005  : J.M. Molines : Original code
+   !!           2.1  : 07/2009  : R. Dussin : add cdf output
+   !!           2.1  : 01/2010  : M.A. Balmaseda : Change integration signs 
+   !!                             so that the transport across a segment is 
+   !!                             independent of the chosen trajectory.
+   !!           3.0  : 04/2011  : J.M. Molines : Doctor norm + Lic.
+   !!----------------------------------------------------------------------
+   !!----------------------------------------------------------------------
+   !!   routines      : description
+   !!  interm_pt  : choose intermediate points on a broken line.
+   !!----------------------------------------------------------------------
+   USE cdfio
+   USE modcdfnames
+   USE modutils       ! for global attribute
+   !!----------------------------------------------------------------------
+   !! CDFTOOLS_3.0 , MEOM 2011
+   !! $Id$
+   !! Copyright (c) 2011, J.-M. Molines
+   !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+   !!----------------------------------------------------------------------
+   IMPLICIT NONE
+
+   INTEGER(KIND=4)                             :: jclass, jseg   ! dummy loop index
+   INTEGER(KIND=4)                             :: ji, jj, jk     ! dummy loop index
+   INTEGER(KIND=4), DIMENSION(:),  ALLOCATABLE :: imeter         ! limit beetween depth level, in m (nclass -1)
+   INTEGER(KIND=4), DIMENSION(:),  ALLOCATABLE :: ilev0, ilev1   ! limit in levels  (nclass)
+   INTEGER(KIND=4), DIMENSION(:),  ALLOCATABLE :: ipk, id_varout ! Netcdf output
+   INTEGER(KIND=4)                             :: ipos           ! working integer (position of ' ' in strings)
+   INTEGER(KIND=4)                             :: ncout, ierr    ! for netcdf output
+   INTEGER(KIND=4)                             :: nvarout=12     ! number of values to write in cdf output
+   INTEGER(KIND=4)                             :: ivtrp          ! var index of volume transport (barotrope)
+   INTEGER(KIND=4)                             :: iptrp          ! var index of volume transport (barotrope)
+   INTEGER(KIND=4)                             :: imtrp          ! var index of volume transport (barotrope)
+   INTEGER(KIND=4)                             :: ihtrp          ! var index of heat transport (barotrope)
+   INTEGER(KIND=4)                             :: istrp          ! var index of sal transport (barotrope)
+   INTEGER(KIND=4)                             :: ivtrpcl        ! var index of volume transport (p. class)
+   INTEGER(KIND=4)                             :: iptrpcl        ! var index of volume transport (p. class)
+   INTEGER(KIND=4)                             :: imtrpcl        ! var index of volume transport (p. class)
+   INTEGER(KIND=4)                             :: ihtrpcl        ! var index of heat transport (p. class)
+   INTEGER(KIND=4)                             :: istrpcl        ! var index of sal transport (p. class)
+   INTEGER(KIND=4)                             :: ilonmin        ! var index of starting section longitude
+   INTEGER(KIND=4)                             :: ilonmax        ! var index of ending section longitude
+   INTEGER(KIND=4)                             :: ilatmin        ! var index of starting section latitude
+   INTEGER(KIND=4)                             :: ilatmax        ! var index of ending section latitude
+   INTEGER(KIND=4)                             :: itop           ! var index of top depth class
+   INTEGER(KIND=4)                             :: ibot           ! var index of bottom depth class
+   INTEGER(KIND=4)                             :: ikx=1, iky=1   ! dims of netcdf output file
+   INTEGER(KIND=4)                             :: numout  = 10   ! logical unit for output file (overall)
+   INTEGER(KIND=4)                             :: numvtrp = 11   ! logical unit for volume transport file
+   INTEGER(KIND=4)                             :: numhtrp = 12   ! logical unit for heat transport file
+   INTEGER(KIND=4)                             :: numstrp = 14   ! logical unit for salt trp file 
+   INTEGER(KIND=4)                             :: nclass         ! number of depth class
+   INTEGER(KIND=4)                             :: narg, iargc    ! command line 
+   INTEGER(KIND=4)                             :: ijarg, nxtarg  !  "       "
+   INTEGER(KIND=4)                             :: npiglo, npjglo ! size of the domain
+   INTEGER(KIND=4)                             :: npk, npt       ! size of the domain
+   INTEGER(KIND=4)                             :: iimin, iimax   ! i-limit of the section
+   INTEGER(KIND=4)                             :: ijmin, ijmax   ! j-limit of the section
+   INTEGER(KIND=4)                             :: ivar, itime    ! working integer
+   INTEGER(KIND=4)                             :: ii, ij, ik     ! working integer
+   INTEGER(KIND=4), PARAMETER                  :: jpseg=10000    ! used for broken line algorithm
+   INTEGER(KIND=4)                             :: ii0, ij0       !  "        "             "
+   INTEGER(KIND=4)                             :: ii1, ij1       !  "        "             "
+   INTEGER(KIND=4)                             :: iitmp, ijtmp   !  "        "             "
+   INTEGER(KIND=4)                             :: np, nn         ! segment counters, 
+   INTEGER(KIND=4)                             :: iist, ijst     ! local point offset for velocity
+   INTEGER(KIND=4)                             :: norm_u, norm_v ! normalization factor (sign of normal transport)
+   INTEGER(KIND=4)                             :: idirx, idiry   ! sense of description of the section
+
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: e1v, e2u       ! horizontal metric
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: e3u, e3v       ! vertical metric
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: glamf          ! longitudes of F points
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: gphif          ! latitudes of F points
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: zu, zut, zus   ! Zonal velocities and uT uS
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: zv, zvt, zvs   ! Meridional velocities and uT uS
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: zt, zs         ! temperature and salinity
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: rdum           ! dummy (1x1) array for ncdf output
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: zuobc, zvobc   ! arrays for OBC files (vertical slice)
+   REAL(KIND=4), DIMENSION(:),     ALLOCATABLE :: tim            ! time counter
+   REAL(KIND=4), DIMENSION(:),     ALLOCATABLE :: gdepw          ! depth at layer interface
+   REAL(KIND=4), DIMENSION(:),     ALLOCATABLE :: e31d           ! vertical metric in case of full step
+   REAL(KIND=4), DIMENSION(:),     ALLOCATABLE :: rclass         ! vertical metric in case of full step
+   REAL(KIND=4), DIMENSION(2)                  :: gla, gphi      ! lon/lat of the begining/end of section (f point)
+   REAL(KIND=4), DIMENSION(jpseg)              :: rxx, ryy       ! working variables
+   REAL(KIND=4)                                :: rxi0, ryj0     ! working variables
+   REAL(KIND=4)                                :: rxi1, ryj1     ! working variables
+   REAL(KIND=4)                                :: ai, bi         ! equation of line (y=ai.x +bi)
+   REAL(KIND=4)                                :: aj, bj         ! equation of line (x=aj.y +bj
+   REAL(KIND=4)                                :: rd, rd1, rd2   ! distance between point, between vertical layers
+   REAL(KIND=4)                                :: udum, vdum     ! dummy velocity components for tests
+   REAL(KIND=4)                                :: rau0=1000      ! density of pure water (kg/m3)
+   REAL(KIND=4)                                :: rcp=4000.      ! heat capacity (J/kg/K)
+
+   ! at every model point
+   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dwku,  dwkv    ! volume transport at each cell boundary
+   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dwkut, dwkvt   ! heat   transport at each cell boundary
+   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dwkus, dwkvs   ! salt   transport at each cell boundary
+   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dwkup, dwkvp   ! volume transport in the positive direction
+   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dwkum, dwkvm   !  volume transport in the negatibe direction
+   REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dtrpu,  dtrpv  ! volume transport integrated in depth class
+   REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dtrput, dtrpvt ! heat transport integrated in depth class
+   REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dtrpus, dtrpvs ! salt transport integrated in depth class
+   REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dtrpup, dtrpvp ! volume transport integrated in depth class (positive)
+   REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dtrpum, dtrpvm ! volume transport integrated in depth class (negative)
+   ! for a given section
+   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dvoltrpsum     ! volume transport by depth class across section
+   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dvoltrpsump    ! volume transport by depth class across section
+   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dvoltrpsumm    ! volume transport by depth class across section
+   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dheatrpsum     ! heat transport by depth class across section
+   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dsaltrpsum     ! salt transport by depth class across section
+   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dvolallegcl    ! over all leg volume transport by depth class
+   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dvolallegclp   ! over all leg volume transport by depth class +
+   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dvolallegclm   ! over all leg volume transport by depth class -
+   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dheatallegcl   ! over all leg heat transport by depth class 
+   REAL(KIND=8), DIMENSION(:),     ALLOCATABLE :: dsaltallegcl   ! over all leg salt transport by depth class 
+   REAL(KIND=8), DIMENSION(jpseg)              :: dvoltrp        ! volume transport across each segment of a section
+   REAL(KIND=8), DIMENSION(jpseg)              :: dvoltrpp       ! volume transport across each segment of a section
+   REAL(KIND=8), DIMENSION(jpseg)              :: dvoltrpm       ! volume transport across each segment of a section
+   REAL(KIND=8), DIMENSION(jpseg)              :: dheatrp        ! heat transport across each segment of a section
+   REAL(KIND=8), DIMENSION(jpseg)              :: dsaltrp        ! salt transport across each segment of a section
+   REAL(KIND=8)                                :: dvoltrpbrtp    ! volume transport integrated over the whole depth
+   REAL(KIND=8)                                :: dvoltrpbrtpp   ! volume transport integrated over the whole depth
+   REAL(KIND=8)                                :: dvoltrpbrtpm   ! volume transport integrated over the whole depth
+   REAL(KIND=8)                                :: dheatrpbrtp    ! heat transport integrated over the whole depth
+   REAL(KIND=8)                                :: dsaltrpbrtp    ! salt transport integrated over the whole depth
+   REAL(KIND=8)                                :: dvolalleg      ! over all leg sum of volume transport
+   REAL(KIND=8)                                :: dvolallegp     ! over all leg sum of volume transport +
+   REAL(KIND=8)                                :: dvolallegm     ! over all leg sum of volume transport -
+   REAL(KIND=8)                                :: dheatalleg     ! over all leg sum of heat transport 
+   REAL(KIND=8)                                :: dsaltalleg     ! over all leg sum of salt transport 
+
+   COMPLEX, DIMENSION(jpseg)                   :: yypt           ! array of points coordinates in a section
+   COMPLEX                                     :: yypti          ! working point
+
+   TYPE(variable), DIMENSION(:),   ALLOCATABLE :: stypvar        ! structure of output
+
+   CHARACTER(LEN=256)                          :: cf_tfil        ! VT file  (in)
+   CHARACTER(LEN=256)                          :: cf_ufil        ! U file   (in)
+   CHARACTER(LEN=256)                          :: cf_vfil        ! V file   (in)
+   CHARACTER(LEN=256)                          :: cf_out='section_trp.dat'  ! output file name (ASCII)
+   CHARACTER(LEN=256)                          :: cf_outnc            ! output netcdf file
+   CHARACTER(LEN=256)                          :: cf_vtrp='vtrp.txt'  ! output volume transport file
+   CHARACTER(LEN=256)                          :: cf_htrp='htrp.txt'  ! output heat transport file
+   CHARACTER(LEN=256)                          :: cf_strp='strp.txt'  ! output salt transport file
+   CHARACTER(LEN=256)                          :: csection            ! section names
+   CHARACTER(LEN=256)                          :: cvarname            ! variable names (root)
+   CHARACTER(LEN=256)                          :: clongname           ! variable longname (root)
+   CHARACTER(LEN=512)                          :: cglobal             ! global attribute
+   CHARACTER(LEN=256)                          :: cldum               ! dummy char variable
+   CHARACTER(LEN=256)                          :: cline               ! dummy char variable
+   CHARACTER(LEN=256), DIMENSION(3)            :: cldumt              ! dummy char variable
+
+   LOGICAL                                     :: ltest   = .FALSE.   ! flag for test case
+   LOGICAL                                     :: lfull   = .FALSE.   ! flag for full step case
+   LOGICAL                                     :: lheat   = .TRUE.    ! flag for skipping heat/salt transport computation
+   LOGICAL                                     :: lchk    = .FALSE.   ! flag for missing files
+   LOGICAL                                     :: lpm     = .FALSE.   ! flag for plus/minus transport
+   LOGICAL                                     :: lobc    = .FALSE.   ! flag for obc input files
+   LOGICAL                                     :: l_merid = .FALSE.   ! flag for meridional obc
+   LOGICAL                                     :: l_zonal = .FALSE.   ! flag for zonal obc
+   LOGICAL                                     :: l_tsfil = .FALSE.   ! flag for using T file instead of VT file
+   LOGICAL                                     :: l_self  = .FALSE.   ! flag for self mesh/mask files in the input
+   !!----------------------------------------------------------------------
+   CALL ReadCdfNames()
+
+   narg= iargc()
+   ! Print usage if no argument
+   IF ( narg == 0 ) THEN
+      PRINT *,' usage : cdftransport [-test  u v ] [-noheat ] [-plus_minus ] [-obc] [-TS] '
+      PRINT *,'                  ... [VT-file] U-file V-file [-full] |-time jt] ...'
+      PRINT *,'                  ... [-time jt ] [-zlimit limits of level] [-self]'
+      PRINT *,'      '
+      PRINT *,'    PURPOSE :'
+      PRINT *,'      Compute the transports accross a section.'
+      PRINT *,'      The name of the section and the imin, imax, jmin, jmax for the section '
+      PRINT *,'      is read from the standard input. To finish the program use the key name'
+      PRINT *,'      ''EOF'' for the section name.'
+      PRINT *,'      OBC U,V files can be used if -obc option is specified.'
+      PRINT *,'      '
+      PRINT *,'     ARGUMENTS :'
+      PRINT *,'      [VT-file ] : netcdf file with mean values of vt, vs, ut, us for heat and'
+      PRINT *,'                   salt transport. If options -noheat or -plus_minus are used'
+      PRINT *,'                   this file name must be omitted.'   
+      PRINT *,'      [U-file ] : netcdf file with the zonal velocity component.'
+      PRINT *,'      [V-file ] : netcdf file with the meridional velocity component.'
+      PRINT *,'      '
+      PRINT *,'     OPTIONS :'
+      PRINT *,'      [-test u v ]: use constant the u and v velocity components for sign '
+      PRINT *,'                    test purpose.'
+      PRINT *,'      [-noheat ]  : use when heat and salt transport are not requested.'
+      PRINT *,'                    This option must come before the file names, and if used'
+      PRINT *,'                    VT file must not be given.'
+      PRINT *,'      [ -plus_minus or -pm ] : separate positive and negative contribution to'
+      PRINT *,'                    the volume transport. This option implicitly set -noheat,'
+      PRINT *,'                    and must be used before the file names.'
+      PRINT *,'      [-obc ]    : indicates that input files are obc files (vertical slices)'
+      PRINT *,'                   Take care that for this case, mesh files must be adapted.'
+      PRINT *,'                   This option implicitly set -noheat, and must be used before'
+      PRINT *,'                   the file names.'
+      PRINT *,'      [ -TS ]    : Indicate that UT VT US VS will be recomputed from T U V '
+      PRINT *,'                   files. T-file is passed as the first file instead of VT '
+      PRINT *,'      [-full ]   :  use for full step configurations.'
+      PRINT *,'      [-time jt ]:  compute transports for time index jt. Default is 1.'
+      PRINT *,'      [-zlimit list of depth] : Specify depths limits defining layers where the'
+      PRINT *,'                    transports will be computed. If not used, the transports '
+      PRINT *,'                    are computed for the whole water column. If used, this '
+      PRINT *,'                    option must be the last on the command line.'  
+      PRINT *,'      [ -self ] : This option indicates that input files corresponds to a '
+      PRINT *,'                  broken line, hence  data files hold the metrics.'
+      PRINT *,'      '
+      PRINT *,'     REQUIRED FILES :'
+      PRINT *,'      Files ',TRIM(cn_fhgr),', ',TRIM(cn_fzgr),' must be in the current directory.'
+      PRINT *,'            unless -self option is used.'
+      PRINT *,'      '
+      PRINT *,'     OUTPUT : '
+      PRINT *,'      - Standard output '
+      PRINT *,'      - ASCII file reflecting the standard output: section_trp.dat'
+      PRINT *,'      - ASCII files for volume, heat and salt transport: vtrp.txt, htrp.txt '
+      PRINT *,'          and strp.txt.'
+      PRINT *,'      - Netcdf files for each section. name of the file is buildt'
+      PRINT *,'          from section name.'
+      PRINT *,'      '
+      PRINT *,'     SEE ALSO :'
+      PRINT *,'       cdfsigtrp cdf_xtrac_brokenline'
+      PRINT *,'      '
+      STOP
+   ENDIF
+
+   itime  = 1
+   nclass = 1
+   ijarg  = 1
+   CALL SetGlobalAtt(cglobal)
+
+   ! Browse command line for arguments and/or options
+   DO WHILE (ijarg <= narg )
+      CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1
+      SELECT CASE ( cldum )
+      CASE ('-test ')
+         CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) udum
+         CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) vdum
+         ltest = .TRUE. 
+
+      CASE ('-full' )
+         lfull = .TRUE.
+
+      CASE ('-noheat' )  ! it must be called before the list of files
+         lheat = .FALSE.
+
+      CASE ('-time' )
+         CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) itime
+
+      CASE ('-plus_minus', '-pm' )
+         lpm   = .TRUE.
+         lheat = .FALSE.
+
+      CASE ('-obc' )
+         lobc  = .TRUE.
+         lheat = .FALSE.
+   
+      CASE ( '-TS' ) 
+         l_tsfil = .TRUE.
+
+      CASE ( '-self' ) 
+         l_self = .TRUE.
+
+      CASE ('-zlimit' )  ! this should be the last option on the line
+         nxtarg = ijarg - 1
+         nclass = narg - nxtarg + 1
+         ALLOCATE ( imeter(nclass -1) ) ! if no zlimit option, this array is never used
+         DO jclass =1, nclass -1
+            CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1 ; READ(cldum,*) imeter(jclass)
+         END DO
+
+      CASE DEFAULT
+         ijarg = ijarg -1 ! re-read argument in this case
+         IF ( lheat) THEN 
+            CALL getarg (ijarg, cf_tfil) ; ijarg = ijarg + 1 
+         ENDIF
+         CALL getarg (ijarg, cf_ufil) ; ijarg = ijarg + 1 
+         CALL getarg (ijarg, cf_vfil) ; ijarg = ijarg + 1 
+      END SELECT
+   END DO
+
+   IF ( l_self ) THEN
+       cn_fzgr = cf_vfil
+       cn_fhgr = cf_vfil
+   ENDIF
+
+   ! checking if all required files are available
+   lchk = lchk .OR. chkfile(cn_fzgr)
+   lchk = lchk .OR. chkfile(cn_fhgr)
+   IF ( ltest ) THEN
+      ! OK
+   ELSE
+      lchk = lchk .OR. chkfile(cf_ufil)
+      lchk = lchk .OR. chkfile(cf_vfil)
+      IF (lheat) THEN
+         lchk = lchk .OR. chkfile(cf_tfil)
+      ENDIF
+   ENDIF
+   IF ( lchk ) STOP ! missing files
+
+   ! adjust the number of output variables according to options
+   IF ( nclass > 1 ) THEN
+      IF ( lheat ) THEN
+         nvarout = 12
+      ELSE 
+         nvarout = 8
+      ENDIF
+      IF ( lpm ) nvarout=nvarout+4
+   ELSE
+      IF ( lheat ) THEN
+         nvarout = 9
+      ELSE 
+         nvarout = 7
+      ENDIF
+      IF ( lpm ) nvarout=nvarout+2
+   ENDIF
+
+   ALLOCATE ( ilev0(nclass), ilev1(nclass), rclass(nclass) )
+   rclass=(/(jclass, jclass=1,nclass)/)
+
+   npiglo = getdim (cf_ufil,cn_x)
+   npjglo = getdim (cf_ufil,cn_y)
+   npk    = getdim (cf_ufil,cn_z)
+   npt    = getdim (cf_ufil,cn_t)
+
+   PRINT *, 'npiglo =', npiglo
+   PRINT *, 'npjglo =', npjglo
+   PRINT *, 'npk    =', npk
+   PRINT *, 'npt    =', npt
+
+   IF ( lobc ) THEN  ! if lobc false, l_merid and l_zonal are false (default)
+      IF ( npiglo == 1 ) THEN
+         l_merid=.TRUE.
+         ALLOCATE (zuobc(npjglo,npk), zvobc(npjglo,npk) )
+         PRINT *,' Meridional OBC'
+      ENDIF
+
+      IF ( npjglo == 1 ) THEN
+         l_zonal=.TRUE.
+         ALLOCATE (zuobc(npiglo,npk), zvobc(npiglo,npk) )
+         PRINT *,' Zonal OBC'
+      ENDIF
+   ENDIF
+
+   ALLOCATE ( e31d(npk) )
+
+   ! define new variables for output 
+   ALLOCATE ( stypvar(nvarout), ipk(nvarout), id_varout(nvarout) )
+   ALLOCATE ( rdum(1,1) )
+
+   rdum(:,:)=0.e0
+
+   ! Allocate arrays
+   ALLOCATE (   zu(npiglo,npjglo),   zv(npiglo,npjglo) )
+   ALLOCATE ( dwku(npiglo,npjglo), dwkv(npiglo,npjglo) )
+   ALLOCATE ( dtrpu(npiglo,npjglo,nclass), dtrpv(npiglo,npjglo,nclass))
+   ALLOCATE ( dvoltrpsum(nclass), dvolallegcl(nclass) )
+
+   IF ( lpm ) THEN 
+      ALLOCATE ( dwkup(npiglo,npjglo), dwkvp(npiglo,npjglo) )
+      ALLOCATE ( dwkum(npiglo,npjglo), dwkvm(npiglo,npjglo) )
+      ALLOCATE ( dtrpup(npiglo,npjglo,nclass), dtrpvp(npiglo,npjglo,nclass))
+      ALLOCATE ( dtrpum(npiglo,npjglo,nclass), dtrpvm(npiglo,npjglo,nclass))
+      ALLOCATE ( dvoltrpsump(nclass),  dvoltrpsumm(nclass)  )
+      ALLOCATE ( dvolallegclp(nclass), dvolallegclm(nclass) )
+   ENDIF
+
+   IF ( lheat ) THEN
+      ALLOCATE (   zut(npiglo,npjglo),   zus(npiglo,npjglo) )
+      ALLOCATE (   zvt(npiglo,npjglo),   zvs(npiglo,npjglo) )
+      ALLOCATE ( dwkut(npiglo,npjglo), dwkus(npiglo,npjglo) )
+      ALLOCATE ( dwkvt(npiglo,npjglo), dwkvs(npiglo,npjglo) )
+      ALLOCATE ( dtrput(npiglo,npjglo,nclass), dtrpvt(npiglo,npjglo,nclass))
+      ALLOCATE ( dtrpus(npiglo,npjglo,nclass), dtrpvs(npiglo,npjglo,nclass))
+      ALLOCATE ( dheatrpsum(nclass), dsaltrpsum(nclass)     )
+      ALLOCATE ( dheatallegcl(nclass), dsaltallegcl(nclass) )
+      IF ( l_tsfil ) THEN
+        ALLOCATE (zt(npiglo+1,npjglo+1), zs(npiglo+1, npjglo+1) )
+      ENDIF
+   ENDIF
+   !
+   ALLOCATE ( e1v(npiglo,npjglo),e3v(npiglo,npjglo)       )
+   ALLOCATE ( e2u(npiglo,npjglo),e3u(npiglo,npjglo)       )
+   !
+   ALLOCATE ( gphif(npiglo,npjglo) )
+   ALLOCATE ( glamf(npiglo,npjglo) )
+   ALLOCATE ( gdepw(npk) , tim(npt)                       )
+   !
+   ! read metrics and grid position
+   e1v(:,:)   = getvar(cn_fhgr, cn_ve1v, 1, npiglo, npjglo)
+   IF ( l_self ) THEN
+     e2u(:,:)   = 1.  ! dummy value, not used
+     glamf(:,:) = 1.
+     gphif(:,:) = 1.
+     ! use e31d for temporary calculation
+     e31d(:)    =  getvar1d(cf_tfil, cn_vdeptht, npk)
+     gdepw(1)   = 0.
+     gdepw(2:npk) = 0.5 * (e31d(1:npk-1) + e31d(2:npk)) ! This is just a proxy for gdepw
+                                                        ! max error ~ 1m for 46 lev
+     e31d(:)    = 1.  ! set dummy value for e31d 
+   ELSE
+     e2u(:,:)   = getvar(cn_fhgr, cn_ve2u, 1, npiglo, npjglo)
+
+     glamf(:,:) = getvar(cn_fhgr, cn_glamf, 1,npiglo, npjglo)
+     gphif(:,:) = getvar(cn_fhgr, cn_gphif, 1,npiglo, npjglo)
+
+     gdepw(:) = getvare3(cn_fzgr, cn_gdepw, npk)
+     e31d(:)  = getvare3(cn_fzgr, cn_ve3t,  npk) ! used only for full step
+   ENDIF
+
+   ! look for nearest level to imeter and setup ilev0 and ilev1 (t-index of class limit)
+   ik = 1
+   ilev0(1) = 1 ; ilev1(nclass) = npk-1  ! default value if nclass=1
+
+   IF ( lobc ) THEN
+      ! read u, v on OBC
+      IF ( l_zonal ) THEN   ! (jpiglo,jpk)
+         zuobc(:,:)= getvarxz(cf_ufil, cn_vozocrtx, 1, npiglo, npk)
+         zvobc(:,:)= getvarxz(cf_vfil, cn_vomecrty, 1, npiglo, npk)
+      ENDIF
+      IF ( l_merid ) THEN   ! (jpjglo,jpk)
+         zuobc(:,:)= getvaryz(cf_ufil, cn_vozocrtx, 1, npjglo, npk)
+         zvobc(:,:)= getvaryz(cf_vfil, cn_vomecrty, 1, npjglo, npk)
+      ENDIF
+   ENDIF
+
+   DO jclass = 1, nclass -1
+      DO WHILE ( gdepw(ik)  < imeter(jclass) )
+         ik = ik +1
+      END DO
+
+      rd1 = ABS(gdepw(ik-1) - imeter(jclass) )
+      rd2 = ABS(gdepw(ik  ) - imeter(jclass) )
+      IF ( rd2 < rd1 ) THEN
+         ilev1(jclass  ) = ik - 1  ! t-levels index
+         ilev0(jclass+1) = ik
+      ELSE 
+         ilev1(jclass  ) = ik - 2  ! t-levels index
+         ilev0(jclass+1) = ik - 1
+      END IF
+   END DO
+
+   PRINT *, 'Limits :  '
+   DO jclass = 1, nclass
+      PRINT *, ilev0(jclass),ilev1(jclass), gdepw(ilev0(jclass)), gdepw(ilev1(jclass)+1)
+   END DO
+
+   ! compute the transports at each grid cell
+   dtrpu (:,:,:)= 0.d0 ; dtrpv (:,:,:)= 0.d0    ! initialization to 0
+
+   IF ( lpm   ) THEN
+      dtrpup(:,:,:)= 0.d0 ; dtrpvp(:,:,:)= 0.d0  
+      dtrpum(:,:,:)= 0.d0 ; dtrpvm(:,:,:)= 0.d0
+   ENDIF
+   IF ( lheat ) THEN
+      dtrput(:,:,:)= 0.d0 ; dtrpvt(:,:,:)= 0.d0  
+      dtrpus(:,:,:)= 0.d0 ; dtrpvs(:,:,:)= 0.d0
+   ENDIF
+
+   DO jclass = 1, nclass
+      DO jk = ilev0(jclass),ilev1(jclass)
+         PRINT *,'level ',jk
+         ! Get velocities, temperature and salinity fluxes at jk
+         IF ( ltest ) THEN
+            zu (:,:) = udum ; zv (:,:) = vdum
+            IF (lheat) THEN
+               zut(:,:) = udum ; zvt(:,:) = vdum
+               zus(:,:) = udum ; zvs(:,:) = vdum
+            ENDIF
+         ELSEIF ( lobc ) THEN
+            IF      ( l_zonal ) THEN ; zu(:,1)=zuobc(:,jk) ; zv(:,1)=zvobc(:,jk) 
+            ELSE IF ( l_merid ) THEN ; zu(1,:)=zuobc(:,jk) ; zv(1,:)=zvobc(:,jk) 
+            ENDIF
+         ELSE
+            IF ( l_self ) THEN
+               zu(:,:) = 0.
+            ELSE
+               zu (:,:) = getvar(cf_ufil, cn_vozocrtx, jk, npiglo, npjglo, ktime=itime)
+            ENDIF
+            zv (:,:) = getvar(cf_vfil, cn_vomecrty, jk, npiglo, npjglo, ktime=itime)
+            IF (lheat) THEN
+               IF ( l_tsfil ) THEN
+                 zt(:,:) = 0. ; zs(:,:) = 0.
+                 zt(1:npiglo,1:npjglo) =  getvar(cf_tfil, cn_votemper, jk, npiglo, npjglo, ktime=itime)
+                 zs(1:npiglo,1:npjglo) =  getvar(cf_tfil, cn_vosaline, jk, npiglo, npjglo, ktime=itime)
+                 zut(1:npiglo,1:npjglo) = zu(1:npiglo,1:npjglo) * 0.5* ( zt(1:npiglo,1:npjglo) + zt(2:npiglo+1,1:npjglo  ))
+                 zus(1:npiglo,1:npjglo) = zu(1:npiglo,1:npjglo) * 0.5* ( zs(1:npiglo,1:npjglo) + zs(2:npiglo+1,1:npjglo  ))
+                 zvt(1:npiglo,1:npjglo) = zv(1:npiglo,1:npjglo) * 0.5* ( zt(1:npiglo,1:npjglo) + zt(1:npiglo,  2:npjglo+1))
+                 zvs(1:npiglo,1:npjglo) = zv(1:npiglo,1:npjglo) * 0.5* ( zs(1:npiglo,1:npjglo) + zs(1:npiglo,  2:npjglo+1))
+               ELSE
+                 IF ( l_self ) THEN
+                     zut(:,:) = 0.
+                     zus(:,:) = 0.
+                 ELSE
+                     zut(:,:) = getvar(cf_tfil, cn_vozout,   jk, npiglo, npjglo, ktime=itime)
+                     zus(:,:) = getvar(cf_tfil, cn_vozous,   jk, npiglo, npjglo, ktime=itime)
+                 ENDIF
+                 zvt(:,:) = getvar(cf_tfil, cn_vomevt,   jk, npiglo, npjglo, ktime=itime)
+                 zvs(:,:) = getvar(cf_tfil, cn_vomevs,   jk, npiglo, npjglo, ktime=itime)
+               ENDIF
+            ENDIF
+         ENDIF
+
+         ! get e3u, e3v  at level jk
+         IF ( lfull ) THEN 
+            e3v(:,:) = e31d(jk)
+            e3u(:,:) = e31d(jk)
+         ELSE
+            IF ( l_self) THEN
+               e3u(:,:) = 1. !dummy value
+               e3v(:,:) = getvar(cn_fzgr, 'e3v_ps', jk, npiglo, npjglo, ldiom=.FALSE.)  ! In broken line name is e3v_ps
+            ELSE
+               e3u(:,:) = getvar(cn_fzgr, 'e3u_ps', jk, npiglo, npjglo, ldiom=.TRUE.)
+               e3v(:,:) = getvar(cn_fzgr, 'e3v_ps', jk, npiglo, npjglo, ldiom=.TRUE.)
+            ENDIF
+         ENDIF
+
+         dwku (:,:) = zu (:,:)*e2u(:,:)*e3u(:,:)*1.d0
+         dwkv (:,:) = zv (:,:)*e1v(:,:)*e3v(:,:)*1.d0
+
+         IF ( lpm ) THEN 
+            dwkup = 0.d0 ; dwkum = 0.d0
+            WHERE ( zu >= 0. ) 
+               dwkup(:,:) = zu (:,:)*e2u(:,:)*e3u(:,:)*1.d0
+            ELSEWHERE 
+               dwkum(:,:) = zu (:,:)*e2u(:,:)*e3u(:,:)*1.d0
+            END WHERE
+
+            dwkvp = 0.d0 ; dwkvm = 0.d0
+            WHERE ( zv >= 0. )
+               dwkvp(:,:) = zv (:,:)*e1v(:,:)*e3v(:,:)*1.d0
+            ELSEWHERE
+               dwkvm(:,:) = zv (:,:)*e1v(:,:)*e3v(:,:)*1.d0
+            END WHERE
+         ENDIF
+
+         IF ( lheat ) THEN
+            dwkut(:,:) = zut(:,:)*e2u(:,:)*e3u(:,:)*1.d0
+            dwkvt(:,:) = zvt(:,:)*e1v(:,:)*e3v(:,:)*1.d0
+            dwkus(:,:) = zus(:,:)*e2u(:,:)*e3u(:,:)*1.d0
+            dwkvs(:,:) = zvs(:,:)*e1v(:,:)*e3v(:,:)*1.d0
+         ENDIF
+
+         ! integrates vertically 
+         dtrpu (:,:,jclass) = dtrpu (:,:,jclass) + dwku (:,:)
+         dtrpv (:,:,jclass) = dtrpv (:,:,jclass) + dwkv (:,:)
+
+         IF ( lpm   ) THEN
+            dtrpup(:,:,jclass) = dtrpup(:,:,jclass) + dwkup(:,:)
+            dtrpvp(:,:,jclass) = dtrpvp(:,:,jclass) + dwkvp(:,:)
+            dtrpum(:,:,jclass) = dtrpum(:,:,jclass) + dwkum(:,:)
+            dtrpvm(:,:,jclass) = dtrpvm(:,:,jclass) + dwkvm(:,:)
+         ENDIF
+
+         IF ( lheat ) THEN
+            dtrput(:,:,jclass) = dtrput(:,:,jclass) + dwkut(:,:) * rau0*rcp
+            dtrpvt(:,:,jclass) = dtrpvt(:,:,jclass) + dwkvt(:,:) * rau0*rcp
+            dtrpus(:,:,jclass) = dtrpus(:,:,jclass) + dwkus(:,:)  
+            dtrpvs(:,:,jclass) = dtrpvs(:,:,jclass) + dwkvs(:,:)  
+         ENDIF
+
+      END DO  ! loop to next level
+   END DO    ! next class
+
+   OPEN(numout,FILE=cf_out)
+   ! also dump the results on txt files without any comments, some users  like it !
+   OPEN(numvtrp,FILE=cf_vtrp)
+   IF ( lheat ) THEN
+      OPEN(numhtrp,FILE=cf_htrp) ; OPEN(numstrp,FILE=cf_strp)
+   ENDIF
+
+   !################################################################################
+   ! enter interactive part 
+   !################################################################################
+   ! initialize all legs arrays and variable to 0 
+   dvolalleg = 0.d0 ; dvolallegcl(:) = 0.d0
+   IF ( lpm   ) THEN
+      dvolallegp = 0.d0 ; dvolallegclp(:) = 0.d0
+      dvolallegm = 0.d0 ; dvolallegclm(:) = 0.d0
+   ENDIF
+   IF ( lheat ) THEN
+      dheatalleg = 0.d0 ; dheatallegcl(:) = 0.d0
+      dsaltalleg = 0.d0 ; dsaltallegcl(:) = 0.d0
+   ENDIF
+   DO 
+      PRINT *, ' Give name of section (EOF to finish)'
+      READ(*,'(a)') cline
+      ii = 0
+      cldumt(:) = 'none'
+      ipos = index(cline,' ')
+      DO WHILE ( ipos > 1 )
+         ii = ii + 1
+         cldumt(ii) = cline(1:ipos - 1 )
+         cline = TRIM ( cline(ipos+1:) )
+         ipos  = index( cline,' ' )
+         IF ( ii >= 3 ) EXIT
+      END DO
+      csection = TRIM(cldumt(1) )
+      cvarname = TRIM(cldumt(2) )
+      clongname = TRIM(cldumt(3) )
+
+      IF (TRIM(csection) == 'EOF' ) THEN 
+         CLOSE(numout) ; CLOSE(numvtrp) 
+         IF ( lheat ) THEN 
+            CLOSE(numhtrp) ; CLOSE(numstrp) 
+         ENDIF
+         EXIT  ! infinite DO loop
+      ENDIF
+
+      ! create output fileset
+      CALL set_typvar( stypvar, csection, cvarname, clongname )
+      cf_outnc = TRIM(csection)//'_transports.nc'
+      ncout    = create      (cf_outnc, 'none',    ikx,      iky, nclass, cdep='depth_class')
+      ierr     = createvar   (ncout,    stypvar,   nvarout,  ipk, id_varout, cdglobal=TRIM(cglobal) )
+      ierr     = putheadervar(ncout,    cf_ufil,   ikx, iky, nclass, pnavlon=rdum, pnavlat=rdum, pdep=rclass )
+      tim      = getvar1d    (cf_ufil,  cn_vtimec, npt     )
+      ierr     = putvar1d    (ncout,    tim(itime:itime),       1, 'T')
+
+      PRINT *, ' Give iimin, iimax, ijmin, ijmax '
+      READ(*,*) iimin, iimax, ijmin, ijmax
+      !! Find the broken line between P1 (iimin,ijmin) and P2 (iimax, ijmax)
+      ! ... Initialization
+      ii0  = iimin ; ij0  = ijmin ; ii1  = iimax ;  ij1 = ijmax
+      rxi0 = ii0   ; ryj0 = ij0   ; rxi1 = ii1   ; ryj1 = ij1
+
+      ! compute direction of integrations and signs
+      !The transport across the section is the dot product of
+      !integral(line){(Mx,My)*dS} 
+      !Mx=integral(u*dz)  My=integral(v*dz)) and dS=(dy,-dx)}
+
+      !By defining the direction of the integration as 
+      idirx = SIGN(1,ii1-ii0) !positive to the east or if ii1=ii0
+      idiry = SIGN(1,ij1-ij0) !positive to the north or if ij1=ij0
+
+      !Then dS=(e2u*idiry,-e1v*idirx)
+      !This will produce the following sign convention:
+      !    West-to-est line (dx>0, dy=0)=> -My*dx (-ve for a northward flow)
+      !    South-to-north   (dy>0, dx=0)=>  Mx*dy (+ve for an eastward flow)
+      norm_u =  idiry
+      norm_v = -idirx
+
+      ! .. Compute equation:  ryj = aj rxi + bj [valid in the (i,j) plane]
+      IF ( (rxi1 -rxi0) /=  0 ) THEN
+         aj = (ryj1 - ryj0 ) / (rxi1 -rxi0)
+         bj = ryj0 - aj * rxi0
+      ELSE
+         aj = 10000.  ! flag value
+         bj = 0.
+      END IF
+
+      ! .. Compute equation:  rxi = ai ryj + bi [valid in the (i,j) plane]
+      IF ( (ryj1 -ryj0) /=  0 ) THEN
+         ai = (rxi1 - rxi0 ) / ( ryj1 -ryj0 )
+         bi = rxi0 - ai * ryj0
+      ELSE
+         ai = 10000. ! flag value
+         bi = 0.
+      END IF
+
+      ! ..  Compute the integer pathway: a succession of F points
+      np=0
+      ! .. Chose the strait line with the smallest slope
+      IF (ABS(aj) <=  1 ) THEN
+         ! ... Here, the best line is y(x)
+         ! ... If ii1 < ii0 swap points [ always describe section from left to right ]
+         IF (ii1 <  ii0 ) THEN
+            iitmp = ii0   ; ijtmp = ij0
+            ii0   = ii1   ; ij0   = ij1
+            ii1   = iitmp ; ij1   = ijtmp
+         END IF
+
+         ! iist,ijst is the grid offset to pass from F point to either U/V point
+         IF ( ij1 >= ij0 ) THEN     ! line heading NE
+            iist = 1 ; ijst = 1
+         ELSE                       ! line heading SE
+            iist = 1 ; ijst = 0
+         END IF
+
+         ! ... compute the nearest ji point on the line crossing at ji
+         DO ji=ii0, ii1
+            np=np+1
+            IF (np > jpseg) STOP 'np > jpseg !'
+            ij=NINT(aj*ji + bj )
+            yypt(np) = CMPLX(ji,ij)
+         END DO
+      ELSE
+         ! ... Here, the best line is x(y)
+         ! ... If ij1 < ij0 swap points [ always describe section from bottom to top ]
+         IF (ij1 <  ij0 ) THEN
+            iitmp = ii0   ; ijtmp = ij0
+            ii0   = ii1   ; ij0   = ij1
+            ii1   = iitmp ; ij1   = ijtmp
+         END IF
+
+         ! iist,ijst is the grid offset to pass from F point to either U/V point
+         IF ( ii1 >=  ii0 ) THEN
+            iist = 1 ; ijst = 1
+         ELSE
+            iist = 0 ; ijst = 1
+         END IF
+
+         ! ... compute the nearest ji point on the line crossing at jj
+         DO jj=ij0,ij1
+            np=np+1
+            IF (np > jpseg) STOP 'np > jpseg !'
+            ii=NINT(ai*jj + bi)
+            yypt(np) = CMPLX(ii,jj)
+         END DO
+      END IF
+
+      !!
+      !! Look for intermediate points to be added.
+      !  ..  The final positions are saved in rxx,ryy
+      rxx(1) = REAL(yypt(1))
+      ryy(1) = IMAG(yypt(1))
+      nn     = 1
+
+      DO jk=2,np
+         ! .. distance between 2 neighbour points
+         rd=ABS(yypt(jk)-yypt(jk-1))
+         ! .. intermediate points required if rd > 1
+         IF ( rd > 1 ) THEN
+            CALL interm_pt(yypt, jk, ai, bi, aj, bj, yypti)
+            nn=nn+1
+            IF (nn > jpseg) STOP 'nn>jpseg !'
+            rxx(nn) = REAL(yypti)
+            ryy(nn) = IMAG(yypti)
+         END IF
+         nn=nn+1
+         IF (nn > jpseg) STOP 'nn>jpseg !'
+         rxx(nn) = REAL(yypt(jk))
+         ryy(nn) = IMAG(yypt(jk))
+      END DO
+      ! record longitude and latitude of initial en endind point of the section
+      gla (1) = glamf( INT(rxx(1)),  INT(ryy(1))  ) 
+      gphi(1) = gphif( INT(rxx(1)),  INT(ryy(1))  ) 
+      gla (2) = glamf( INT(rxx(nn)), INT(ryy(nn)) ) 
+      gphi(2) = gphif( INT(rxx(nn)), INT(ryy(nn)) ) 
+
+      ! Now extract the transport through a section 
+      ! ... Check whether we need a u velocity or a v velocity
+      !   Think that the points are f-points and delimit either a U segment
+      !   or a V segment (iist and ijst are set in order to look for the correct
+      !   velocity point on the C-grid
+      PRINT *, TRIM(csection)
+      PRINT *, 'IMIN IMAX JMIN JMAX', iimin, iimax, ijmin, ijmax
+      WRITE(numout,*) '% Transport along a section by levels' ,TRIM(csection)
+      WRITE(numout,*) '% ---- IMIN IMAX JMIN JMAX'
+
+      dvoltrpbrtp  = 0.d0
+      dvoltrpbrtpp = 0.d0
+      dvoltrpbrtpm = 0.d0
+      dheatrpbrtp  = 0.d0
+      dsaltrpbrtp  = 0.d0
+      DO jclass=1,nclass
+         dvoltrpsum(jclass) = 0.d0
+         IF ( lpm   ) THEN
+            dvoltrpsump(jclass) = 0.d0
+            dvoltrpsumm(jclass) = 0.d0
+         ENDIF
+         IF ( lheat ) THEN
+            dheatrpsum(jclass) = 0.d0
+            dsaltrpsum(jclass) = 0.d0
+         ENDIF
+
+         ! segment jseg is a line between (rxx(jseg),ryy(jseg))  and (rxx(jseg+1),ryy(jseg+1))
+         DO jseg = 1, nn-1
+            ii0=rxx(jseg)
+            ij0=ryy(jseg)
+            IF ( rxx(jseg) ==  rxx(jseg+1) ) THEN    ! meridional segment, use U velocity
+               dvoltrp(jseg)= dtrpu (ii0,ij0+ijst,jclass)*norm_u
+
+               IF ( lpm   ) THEN 
+                  IF (norm_u > 0 ) THEN
+                    dvoltrpp(jseg)= dtrpup(ii0,ij0+ijst,jclass)*norm_u
+                    dvoltrpm(jseg)= dtrpum(ii0,ij0+ijst,jclass)*norm_u
+                  ELSE
+                    dvoltrpp(jseg)= dtrpum(ii0,ij0+ijst,jclass)*norm_u
+                    dvoltrpm(jseg)= dtrpup(ii0,ij0+ijst,jclass)*norm_u
+                  ENDIF
+               ENDIF
+
+               IF ( lheat ) THEN
+                  dheatrp(jseg)= dtrput(ii0,ij0+ijst,jclass)*norm_u
+                  dsaltrp(jseg)= dtrpus(ii0,ij0+ijst,jclass)*norm_u
+               ENDIF
+            ELSE IF ( ryy(jseg) == ryy(jseg+1) ) THEN ! zonal segment, use V velocity
+               dvoltrp(jseg)=dtrpv (ii0+iist,ij0,jclass)*norm_v
+
+               IF ( lpm   ) THEN 
+                 IF (norm_v > 0 ) THEN
+                    dvoltrpp(jseg)=dtrpvp(ii0+iist,ij0,jclass)*norm_v
+                    dvoltrpm(jseg)=dtrpvm(ii0+iist,ij0,jclass)*norm_v
+                 ELSE
+                    dvoltrpp(jseg)=dtrpvm(ii0+iist,ij0,jclass)*norm_v
+                    dvoltrpm(jseg)=dtrpvp(ii0+iist,ij0,jclass)*norm_v
+                 ENDIF
+               ENDIF
+
+               IF ( lheat ) THEN
+                  dheatrp(jseg)=dtrpvt(ii0+iist,ij0,jclass)*norm_v
+                  dsaltrp(jseg)=dtrpvs(ii0+iist,ij0,jclass)*norm_v
+               ENDIF
+            ELSE
+               PRINT *,' ERROR :',  rxx(jseg),ryy(jseg),rxx(jseg+1),ryy(jseg+1) ! likely to never happen !
+            END IF
+            dvoltrpsum(jclass) = dvoltrpsum(jclass) + dvoltrp(jseg)
+            IF ( lpm   ) THEN 
+               dvoltrpsump(jclass) = dvoltrpsump(jclass) + dvoltrpp(jseg)
+               dvoltrpsumm(jclass) = dvoltrpsumm(jclass) + dvoltrpm(jseg)
+            ENDIF
+            IF ( lheat ) THEN
+               dheatrpsum(jclass) = dheatrpsum(jclass) + dheatrp(jseg)
+               dsaltrpsum(jclass) = dsaltrpsum(jclass) + dsaltrp(jseg)
+            ENDIF
+         END DO   ! next segment
+
+         ! Ascii outputs :      
+         IF (jclass == 1 ) THEN   ! print header when it is the first class
+            PRINT '(a,2f8.2,a,2f8.2)', 'FROM (LON LAT): ', gla(1),gphi(1),' TO (LON LAT) ', gla(2), gphi(2)
+            WRITE(numout,*)  '% ---- LONmin LATmin LONmax LATmax'
+            WRITE(numout,*)  '% Top(m)  Bottom(m)  MassTrans(Sv) HeatTrans(PW) SaltTrans(kt/s)'
+            WRITE(numout,*) 0 ,iimin, iimax, ijmin, ijmax
+            WRITE(numout,9003) 0. ,gla(1),gphi(1), gla(2), gphi(2)
+         ENDIF
+
+         PRINT *, gdepw(ilev0(jclass)), gdepw(ilev1(jclass)+1)
+         PRINT *, ' Mass transport : ', dvoltrpsum(jclass)/1.e6,' SV'
+         WRITE(numvtrp,'(e14.6)') dvoltrpsum(jclass) 
+         IF ( lpm   ) THEN
+            PRINT *, ' Positive Mass transport : ', dvoltrpsump(jclass)/1.e6,' SV'
+            PRINT *, ' Negative Mass transport : ', dvoltrpsumm(jclass)/1.e6,' SV'
+            WRITE(numout,9002) gdepw(ilev0(jclass)), gdepw(ilev1(jclass)+1), &
+                 &   dvoltrpsum(jclass)/1.e6, dvoltrpsump(jclass)/1.e6, dvoltrpsumm(jclass)/1.e6
+            WRITE(numvtrp,'(e14.6)') dvoltrpsump(jclass) 
+            WRITE(numvtrp,'(e14.6)') dvoltrpsumm(jclass) 
+         ENDIF
+
+         IF ( lheat ) THEN
+            PRINT *, ' Heat transport : ', dheatrpsum(jclass)/1.e15,' PW'
+            PRINT *, ' Salt transport : ', dsaltrpsum(jclass)/1.e6,' kT/s'
+            WRITE(numout,9002) gdepw(ilev0(jclass)), gdepw(ilev1(jclass)+1), &
+                 &   dvoltrpsum(jclass)/1.e6, dheatrpsum(jclass)/1.e15, dsaltrpsum(jclass)/1.e6
+            WRITE(numhtrp,'(e14.6)') dheatrpsum(jclass)
+            WRITE(numstrp,'(e14.6)') dsaltrpsum(jclass)
+         ELSE
+            IF ( .NOT. lpm ) WRITE(numout,9002) gdepw(ilev0(jclass)), gdepw(ilev1(jclass)+1), dvoltrpsum(jclass)/1.e6
+         ENDIF
+
+         ! netcdf output 
+         IF ( nclass > 1 ) THEN
+            rdum(1,1) = REAL(dvoltrpsum(jclass)/1.e6)
+            ierr = putvar(ncout,id_varout(ivtrpcl), rdum, jclass, 1, 1, 1 ) 
+            IF ( lpm   ) THEN
+               rdum(1,1) =  REAL(dvoltrpsump(jclass)/1.e6)
+               ierr = putvar(ncout,id_varout(iptrpcl), rdum, jclass, 1, 1, 1 ) 
+               rdum(1,1) =  REAL(dvoltrpsumm(jclass)/1.e6)
+               ierr = putvar(ncout,id_varout(imtrpcl), rdum, jclass, 1, 1, 1 ) 
+            ENDIF
+            IF ( lheat ) THEN
+               rdum(1,1) =  REAL(dheatrpsum(jclass)/1.e15)
+               ierr = putvar(ncout,id_varout(ihtrpcl), rdum, jclass, 1, 1, 1 ) 
+               rdum(1,1) =  REAL(dsaltrpsum(jclass)/1.e6)
+               ierr = putvar(ncout,id_varout(istrpcl), rdum, jclass, 1, 1, 1 )
+            ENDIF
+         ENDIF
+         rdum(1,1) = REAL(gdepw(ilev0(jclass)))
+         ierr = putvar(ncout,id_varout(itop), rdum, jclass, 1, 1, 1 )
+         rdum(1,1) = REAL(gdepw(ilev1(jclass)+1))
+         ierr = putvar(ncout,id_varout(ibot), rdum, jclass, 1, 1, 1 )
+
+         dvoltrpbrtp = dvoltrpbrtp +  dvoltrpsum(jclass)
+         IF ( lpm  ) THEN
+            dvoltrpbrtpp = dvoltrpbrtpp + dvoltrpsump(jclass)
+            dvoltrpbrtpm = dvoltrpbrtpm + dvoltrpsumm(jclass)
+         ENDIF
+         IF ( lheat) THEN
+            dheatrpbrtp = dheatrpbrtp +  dheatrpsum(jclass)
+            dsaltrpbrtp = dsaltrpbrtp +  dsaltrpsum(jclass)
+         ENDIF
+         ! save sum over legs
+         dvolallegcl(jclass) = dvolallegcl(jclass) + dvoltrpsum(jclass)
+         IF ( lpm   ) THEN
+            dvolallegclp(jclass) = dvolallegclp(jclass) + dvoltrpsump(jclass)
+            dvolallegclm(jclass) = dvolallegclm(jclass) + dvoltrpsumm(jclass)
+         ENDIF
+         IF ( lheat ) THEN
+            dheatallegcl(jclass) = dheatallegcl(jclass) + dheatrpsum(jclass)
+            dsaltallegcl(jclass) = dsaltallegcl(jclass) + dsaltrpsum(jclass)
+         ENDIF
+      END DO ! next class
+      ! save sum over legs 
+      dvolalleg = dvolalleg + dvoltrpbrtp
+      IF ( lpm   ) THEN
+         dvolallegp = dvolallegp + dvoltrpbrtpp
+         dvolallegm = dvolallegm + dvoltrpbrtpm
+      ENDIF
+      IF ( lheat ) THEN
+         dheatalleg = dheatalleg + dheatrpbrtp
+         dsaltalleg = dsaltalleg + dsaltrpbrtp
+      ENDIF
+
+      IF ( nclass > 1 ) THEN 
+         PRINT *, ' ====================================================='
+         PRINT *, ' total Mass transport : ', dvoltrpbrtp/1.e6,' SV'
+         IF ( lpm   ) THEN
+            PRINT *, ' total positive transport : ', dvoltrpbrtpp/1.e6,' SV'
+            PRINT *, ' total negative transport : ', dvoltrpbrtpm/1.e6,' SV'
+         ENDIF
+         IF ( lheat ) THEN
+            PRINT *, ' total Heat transport : ', dheatrpbrtp/1.e15,' PW'
+            PRINT *, ' total Salt transport : ', dsaltrpbrtp/1.e6,' kT/s'
+         ENDIF
+      ENDIF
+      ierr = putvar0d(ncout,id_varout(ivtrp), REAL(dvoltrpbrtp/1.e6)        )
+      IF ( lpm   ) THEN
+         ierr = putvar0d(ncout,id_varout(iptrp), REAL(dvoltrpbrtpp/1.e6)    )
+         ierr = putvar0d(ncout,id_varout(imtrp), REAL(dvoltrpbrtpm/1.e6)    )
+      ENDIF
+      IF ( lheat ) THEN
+         ierr = putvar0d(ncout,id_varout(ihtrp), REAL(dheatrpbrtp/1.e15)    )
+         ierr = putvar0d(ncout,id_varout(istrp), REAL(dsaltrpbrtp/1.e6 )    )
+      ENDIF
+      ierr = putvar0d(ncout,id_varout(ilonmin), REAL(gla(1))  )
+      ierr = putvar0d(ncout,id_varout(ilonmax), REAL(gla(2))  )
+      ierr = putvar0d(ncout,id_varout(ilatmin), REAL(gphi(1)) )
+      ierr = putvar0d(ncout,id_varout(ilatmax), REAL(gphi(2)) )
+      ierr = closeout(ncout)
+   END DO ! infinite loop : gets out when input is EOF 
+
+
+   PRINT *,'   '
+   PRINT *,' Overall transports (sum of all legs done so far)'
+   DO jclass = 1, nclass
+      PRINT *, gdepw(ilev0(jclass)), gdepw(ilev1(jclass)+1)
+      PRINT *, ' Mass transport : ', dvolallegcl(jclass)/1.e6,' SV'
+      IF ( lpm   ) THEN
+         PRINT *, ' Positive Mass transport : ', dvolallegclp(jclass)/1.e6,' SV'
+         PRINT *, ' Negative Mass transport : ', dvolallegclm(jclass)/1.e6,' SV'
+      ENDIF
+
+      IF ( lheat ) THEN
+         PRINT *, ' Heat transport : ', dheatallegcl(jclass)/1.e15,' PW'
+         PRINT *, ' Salt transport : ', dsaltallegcl(jclass)/1.e6,' kT/s'
+      ENDIF
+   ENDDO
+
+   IF ( nclass > 1 ) THEN
+      PRINT *, ' ====================================================='
+      PRINT *, '    Mass transport      : ', dvolalleg/1.e6,' SV'
+      IF ( lpm ) THEN
+         PRINT *, '     positive transport : ', dvolallegp/1.e6,' SV'
+         PRINT *, '     negative transport : ', dvolallegm/1.e6,' SV'
+      ENDIF
+      IF ( lheat ) THEN
+         PRINT *, '     heat transport     : ', dheatalleg/1.e15,' PW'
+         PRINT *, '     salt transport     : ', dsaltalleg/1.e6,' kT/s'
+      ENDIF
+   ENDIF
+
+
+9000 FORMAT(I4,6(f9.3,f8.4))
+9001 FORMAT(I4,6(f9.2,f9.3))
+9002 FORMAT(f9.0,f9.0,f9.2,f9.2,f9.2)
+9003 FORMAT(f9.2,f9.2,f9.2,f9.2,f9.2)
+
+CONTAINS
+   SUBROUTINE set_typvar ( sd_typvar, cdsection, cdvarname, cdlongname ) 
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE set_typvar  ***
+      !!
+      !! ** Purpose : Initialize typvar structure for netcdfoutput at a given section
+      !!
+      !! ** Method  : use varname longname to suffix variable name and attributes
+      !!              If varname and/or logname are not given (ie 'none') take
+      !!              standard default names
+      !!              Netcdf id for variables are passed as global variables
+      !!----------------------------------------------------------------------
+      TYPE(variable), DIMENSION(:), INTENT(out) :: sd_typvar        ! structure of output
+      CHARACTER(LEN=*),             INTENT(in ) :: cdsection
+      CHARACTER(LEN=*),             INTENT(in ) :: cdvarname
+      CHARACTER(LEN=*),             INTENT(in ) :: cdlongname
+      !!
+      INTEGER(KIND=4)                           :: ivar
+      CHARACTER(LEN=255)                        :: csuffixvarnam
+      CHARACTER(LEN=255)                        :: cprefixlongnam
+      !!----------------------------------------------------------------------
+      ! set suffixes according to variable/longname 
+      IF ( cdvarname /= 'none' ) THEN
+         csuffixvarnam = '_'//TRIM(cdvarname)
+      ELSE
+         csuffixvarnam = ''
+      ENDIF
+
+      IF ( cdlongname /= 'none' ) THEN
+         cprefixlongnam = TRIM(cdlongname)//'_'
+      ELSE
+         cprefixlongnam = ''
+      ENDIF
+
+      ! set common values
+      sd_typvar%rmissing_value=99999.
+      sd_typvar%scale_factor= 1.
+      sd_typvar%add_offset= 0.
+      sd_typvar%savelog10= 0.
+      sd_typvar%conline_operation='N/A'
+      sd_typvar%caxis='T'
+
+      ! set particular values for individual variables
+      ivar = 1  ; ivtrp = ivar
+      ipk(ivar) = 1
+      sd_typvar(ivar)%cname       = 'vtrp'//TRIM(csuffixvarnam)
+      sd_typvar(ivar)%cunits      = 'Sverdrup'
+      sd_typvar(ivar)%valid_min   = -500.
+      sd_typvar(ivar)%valid_max   =  500.
+      sd_typvar(ivar)%clong_name  = TRIM(cprefixlongnam)//'Volume_Transport'
+      sd_typvar(ivar)%cshort_name = 'vtrp'
+
+      IF ( lpm ) THEN 
+         ivar = ivar + 1 ; iptrp = ivar                                                  ;  imtrp = ivar+1
+         ipk(ivar) = 1                                                                   ;  ipk(ivar+1) = 1
+         sd_typvar(ivar)%cname       = 'ptrp'//TRIM(csuffixvarnam)                       ;  sd_typvar(ivar+1)%cname       = 'mtrp'//TRIM(csuffixvarnam)
+         sd_typvar(ivar)%cunits      = 'Sverdrup'                                        ;  sd_typvar(ivar+1)%cunits      = 'Sverdrup'
+         sd_typvar(ivar)%valid_min   = -500.                                             ;  sd_typvar(ivar+1)%valid_min   = -500.
+         sd_typvar(ivar)%valid_max   =  500.                                             ;  sd_typvar(ivar+1)%valid_max   =  500.
+         sd_typvar(ivar)%clong_name  = TRIM(cprefixlongnam)//'Positive_volume_transport' ;  sd_typvar(ivar+1)%clong_name  = TRIM(cprefixlongnam)//'Negative_volume_transport'
+         sd_typvar(ivar)%cshort_name = 'ptrp'                                            ;  sd_typvar(ivar+1)%cshort_name = 'mtrp'
+         ivar = ivar + 1
+      ENDIF
+
+      IF ( lheat ) THEN
+         ivar = ivar + 1 ; ihtrp = ivar                                                  ;  istrp = ivar+1
+         ipk(ivar) = 1                                                                   ;  ipk(ivar+1) = 1
+         sd_typvar(ivar)%cname       = 'htrp'//TRIM(csuffixvarnam)                       ;  sd_typvar(ivar+1)%cname       = 'strp'//TRIM(csuffixvarnam)
+         sd_typvar(ivar)%cunits      = 'PW'                                              ;  sd_typvar(ivar+1)%cunits      = 'kt/s'
+         sd_typvar(ivar)%valid_min   = -1000.                                            ;  sd_typvar(ivar+1)%valid_min   = -1000.
+         sd_typvar(ivar)%valid_max   =  1000.                                            ;  sd_typvar(ivar+1)%valid_max   =  1000.
+         sd_typvar(ivar)%clong_name  = TRIM(cprefixlongnam)//'Heat_Transport'            ;  sd_typvar(ivar+1)%clong_name  = TRIM(cprefixlongnam)//'Salt_Transport'
+         sd_typvar(ivar)%cshort_name = 'htrp'                                            ;  sd_typvar(ivar+1)%cshort_name = 'strp'
+         ivar = ivar + 1
+      ENDIF
+
+      ivar = ivar + 1 ; ilonmin = ivar                                                   ;  ilonmax = ivar+1
+      ipk(ivar) = 1                                                                      ;  ipk(ivar+1) = 1
+      sd_typvar(ivar)%cname       = 'lonmin'//TRIM(csuffixvarnam)                        ;  sd_typvar(ivar+1)%cname       = 'lonmax'//TRIM(csuffixvarnam)
+      sd_typvar(ivar)%cunits      = 'deg'                                                ;  sd_typvar(ivar+1)%cunits      = 'deg'
+      sd_typvar(ivar)%valid_min   = -180.                                                ;  sd_typvar(ivar+1)%valid_min   = -180.
+      sd_typvar(ivar)%valid_max   =  180.                                                ;  sd_typvar(ivar+1)%valid_max   =  180.
+      sd_typvar(ivar)%clong_name  = TRIM(cprefixlongnam)//'begin_longitude'              ;  sd_typvar(ivar+1)%clong_name  = TRIM(cprefixlongnam)//'end_longitude'
+      sd_typvar(ivar)%cshort_name = 'lonmin'                                             ;  sd_typvar(ivar+1)%cshort_name = 'lonmax'
+      ivar = ivar + 1
+
+      ivar = ivar + 1  ; ilatmin = ivar                                                  ;  ilatmax = ivar+1
+      ipk(ivar) = 1                                                                      ;  ipk(ivar+1) = 1
+      sd_typvar(ivar)%cname       = 'latmin'//TRIM(csuffixvarnam)                        ;  sd_typvar(ivar+1)%cname       = 'latmax'//TRIM(csuffixvarnam)
+      sd_typvar(ivar)%cunits      = 'deg'                                                ;  sd_typvar(ivar+1)%cunits      = 'deg'
+      sd_typvar(ivar)%valid_min   = -90.                                                 ;  sd_typvar(ivar+1)%valid_min   = -90.
+      sd_typvar(ivar)%valid_max   =  90.                                                 ;  sd_typvar(ivar+1)%valid_max   =  90.
+      sd_typvar(ivar)%clong_name  = TRIM(cprefixlongnam)//'begin_latitude'               ;  sd_typvar(ivar+1)%clong_name  = TRIM(cprefixlongnam)//'end_latitude'
+      sd_typvar(ivar)%cshort_name = 'latmin'                                             ;  sd_typvar(ivar+1)%cshort_name = 'latmax'
+      ivar = ivar + 1
+
+      ivar = ivar + 1  ; itop = ivar                                                     ;  ibot = ivar+1
+      ipk(ivar) = nclass                                                                 ;  ipk(ivar+1) = nclass
+      sd_typvar(ivar)%cname       = 'top'                                                ;  sd_typvar(ivar+1)%cname       = 'bottom'
+      sd_typvar(ivar)%cunits      = 'meters'                                             ;  sd_typvar(ivar+1)%cunits      = 'meters'
+      sd_typvar(ivar)%valid_min   = 0.                                                   ;  sd_typvar(ivar+1)%valid_min   = 0.
+      sd_typvar(ivar)%valid_max   = 10000.                                               ;  sd_typvar(ivar+1)%valid_max   = 10000.
+      sd_typvar(ivar)%clong_name  = 'class_min_depth'                                    ;  sd_typvar(ivar+1)%clong_name  = 'class_max_depth'
+      sd_typvar(ivar)%cshort_name = 'top'                                                ;  sd_typvar(ivar+1)%cshort_name = 'bottom'
+      ivar = ivar + 1
+
+      ivtrpcl = -1  ; ihtrpcl = -1 ; istrpcl = -1
+      IF ( nclass > 1 ) THEN  ! define additional variable for vertical profile of transport (per class)
+         ivar = ivar + 1  ; ivtrpcl = ivar
+         ipk(ivar) = nclass                      
+         sd_typvar(ivar)%cname       = 'vtrp_dep'//TRIM(csuffixvarnam) 
+         sd_typvar(ivar)%cunits      = 'SV'  
+         sd_typvar(ivar)%valid_min   = 0.       
+         sd_typvar(ivar)%valid_max   = 10000.  
+         sd_typvar(ivar)%clong_name  = TRIM(cprefixlongnam)//'Volume_Transport_per_class' 
+         sd_typvar(ivar)%cshort_name = 'vtrp_dep'            
+
+         IF ( lpm )  THEN
+            ivar = ivar + 1  ; iptrpcl = ivar                                             ;  imtrpcl = ivar+1
+            ipk(ivar) = nclass                                                            ;  ipk(ivar+1) = nclass
+            sd_typvar(ivar)%cname       = 'ptrp_dep'//TRIM(csuffixvarnam)                 ;  sd_typvar(ivar+1)%cname       = 'mtrp_dep'//TRIM(csuffixvarnam)
+            sd_typvar(ivar)%cunits      = 'SV'                                            ;  sd_typvar(ivar+1)%cunits      = 'SV'
+            sd_typvar(ivar)%valid_min   = -500.                                           ;  sd_typvar(ivar+1)%valid_min   = -500.
+            sd_typvar(ivar)%valid_max   =  500.                                           ;  sd_typvar(ivar+1)%valid_max   =  500.
+            sd_typvar(ivar)%clong_name  = TRIM(cprefixlongnam)//'Positive_trp_per_class'  ;  sd_typvar(ivar+1)%clong_name  = TRIM(cprefixlongnam)//'Negative_trp_per_class'
+            sd_typvar(ivar)%cshort_name = 'ptrp_dep'                                      ;  sd_typvar(ivar+1)%cshort_name = 'mtrp_dep'
+            ivar = ivar + 1
+         ENDIF
+
+         IF ( lheat ) THEN
+            ivar = ivar + 1  ; ihtrpcl = ivar                                              ;  istrpcl = ivar+1
+            ipk(ivar) = nclass                                                             ;  ipk(ivar+1) = nclass
+            sd_typvar(ivar)%cname       = 'htrp_dep'//TRIM(csuffixvarnam)                  ;  sd_typvar(ivar+1)%cname       = 'strp_dep'//TRIM(csuffixvarnam)
+            sd_typvar(ivar)%cunits      = 'PW'                                             ;  sd_typvar(ivar+1)%cunits      = 'kt/s'
+            sd_typvar(ivar)%valid_min   = -1000.                                           ;  sd_typvar(ivar+1)%valid_min   = -1000.
+            sd_typvar(ivar)%valid_max   =  1000.                                           ;  sd_typvar(ivar+1)%valid_max   =  1000.
+            sd_typvar(ivar)%clong_name  = TRIM(cprefixlongnam)//'Heat_Transport_per_class' ;  sd_typvar(ivar+1)%clong_name  = TRIM(cprefixlongnam)//'Salt_Transport_per_class'
+            sd_typvar(ivar)%cshort_name = 'htrp_dep'                                       ;  sd_typvar(ivar+1)%cshort_name = 'strp_dep'
+            ivar = ivar + 1
+         ENDIF
+      ENDIF
+
+   END SUBROUTINE set_typvar
+   SUBROUTINE interm_pt (ydpt, kk, pai, pbi, paj, pbj, ydpti)
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE nterm_pt  ***
+      !!
+      !! ** Purpose : Find the best intermediate points on a pathway.
+      !!
+      !! ** Method  : ydpt : complex vector of the positions of the nearest points
+      !!               kk  : current working index
+      !!          pai, pbi : slope and original ordinate of x(y)
+      !!          paj, pbj : slope and original ordinate of y(x)
+      !!             ydpti : Complex holding the position of intermediate point 
+      !!
+      !! ** Reference : 19/07/1999 : J.M. Molines in Clipper
+      !!----------------------------------------------------------------------
+      COMPLEX, DIMENSION(:), INTENT(in ) :: ydpt
+      COMPLEX,               INTENT(out) :: ydpti
+      REAL(KIND=4),          INTENT(in ) :: pai, pbi, paj, pbj
+      INTEGER(KIND=4),       INTENT(in ) :: kk
+      ! ... local
+      COMPLEX                            :: ylptmp1, ylptmp2
+      REAL(KIND=4)                       :: za0, zb0
+      REAL(KIND=4)                       :: za1, zb1
+      REAL(KIND=4)                       :: zd1, zd2
+      REAL(KIND=4)                       :: zxm, zym
+      REAL(KIND=4)                       :: zxp, zyp
+      !!----------------------------------------------------------------------
+      ! ... Determines whether we use y(x) or x(y):
+      IF (ABS(paj) <=  1) THEN
+         ! .....  use y(x)
+         ! ... possible intermediate points:
+         ylptmp1=ydpt(kk-1)+(1.,0.)                 ! M1 
+         ylptmp2=ydpt(kk-1)+CMPLX(0.,SIGN(1.,paj))  ! M2
+         !
+         ! ... M1 is the candidate point:
+         zxm=REAL(ylptmp1)
+         zym=IMAG(ylptmp1)
+         za0=paj
+         zb0=pbj
+         !
+         za1=-1./za0
+         zb1=zym - za1*zxm
+         ! ... P1 is the projection of M1 on the strait line
+         zxp=-(zb1-zb0)/(za1-za0)
+         zyp=za0*zxp + zb0
+         ! ... zd1 is the distance M1P1
+         zd1=(zxm-zxp)*(zxm-zxp) + (zym-zyp)*(zym-zyp)
+         !
+         ! ... M2 is the candidate point:
+         zxm=REAL(ylptmp2)
+         zym=IMAG(ylptmp2)
+         za1=-1./za0
+         zb1=zym - za1*zxm
+         ! ... P2 is the projection of M2 on the strait line
+         zxp=-(zb1-zb0)/(za1-za0)
+         zyp=za0*zxp + zb0
+         ! ... zd2 is the distance M2P2
+         zd2=(zxm-zxp)*(zxm-zxp) + (zym-zyp)*(zym-zyp)
+         ! ... chose the smallest (zd1,zd2)
+         IF (zd2 <=  zd1) THEN
+            ydpti=ylptmp2   ! use M2
+         ELSE
+            ydpti=ylptmp1   ! use M1
+         END IF
+         !
+      ELSE   
+         ! ...  use x(y)
+         ! ... possible intermediate points:
+         ylptmp1=ydpt(kk-1)+CMPLX(SIGN(1.,pai),0.)  ! M1
+         ylptmp2=ydpt(kk-1)+(0.,1.)                 ! M2
+         ! 
+         ! ... M1 is the candidate point:
+         zxm=REAL(ylptmp1)
+         zym=IMAG(ylptmp1)
+         za0=pai
+         zb0=pbi
+         !
+         za1=-1./za0
+         zb1=zxm - za1*zym
+         zyp=-(zb1-zb0)/(za1-za0)
+         zxp=za0*zyp + zb0
+         zd1=(zxm-zxp)*(zxm-zxp) + (zym-zyp)*(zym-zyp)
+         !
+         zxm=REAL(ylptmp2)
+         zym=IMAG(ylptmp2)
+         za1=-1./za0
+         zb1=zxm - za1*zym
+         zyp=-(zb1-zb0)/(za1-za0)
+         zxp=za0*zyp + zb0
+         zd2=(zxm-zxp)*(zxm-zxp) + (zym-zyp)*(zym-zyp)
+         IF (zd2 <=  zd1) THEN
+            ydpti=ylptmp2
+         ELSE
+            ydpti=ylptmp1
+         END IF
+      END IF
+   END SUBROUTINE interm_pt
+
+END PROGRAM cdftransport
diff --git a/cdfvT.f90 b/src/cdfuv.f90
similarity index 58%
copy from cdfvT.f90
copy to src/cdfuv.f90
index 7e97310..5db7739 100644
--- a/cdfvT.f90
+++ b/src/cdfuv.f90
@@ -1,10 +1,9 @@
-PROGRAM cdfvT
+PROGRAM cdfuv
   !!======================================================================
-  !!                     ***  PROGRAM  cdfvT  ***
+  !!                     ***  PROGRAM  cdfuv  ***
   !!=====================================================================
   !!  ** Purpose : Compute the average values for the products 
-  !!               V.T, V.S, U.T and U.S, used afterward for heat and
-  !!               salt transport.
+  !!               u.v at T-point
   !!
   !!  ** Method  : pass the CONFIG name and a series of tags as arguments.
   !!
@@ -33,45 +32,47 @@ PROGRAM cdfvT
   INTEGER(KIND=4)                           :: ncout                ! ncid of output file
   INTEGER(KIND=4), DIMENSION(4)             :: ipk, id_varout       ! level and varid's of output vars
 
-  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: ztemp, zsal          ! Array to read a layer of data
   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zu, zv               ! Velocity component
   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zworku, zworkv       ! working arrays
   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zmean                ! temporary mean value for netcdf write
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zlon                 ! longitude of T points to check periodicity
   REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim                  ! time counter of individual files
   REAL(KIND=4), DIMENSION(1)                :: timean               ! mean time
 
-  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dcumulut, dcumulus   ! Arrays for cumulated values
-  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dcumulvt, dcumulvs   ! Arrays for cumulated values
+  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dcumuluv             ! Arrays for cumulated values
+  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dcumulu              ! Arrays for cumulated values
+  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dcumulv              ! Arrays for cumulated values
+  REAL(KIND=8), DIMENSION(:,:), ALLOCATABLE :: dupvp                ! Arrays for U'.V'
   REAL(KIND=8)                              :: dtotal_time          ! cumulated time
 
-  CHARACTER(LEN=256)                        :: cf_tfil              ! T file name
-  CHARACTER(LEN=256)                        :: cf_sfil              ! S file name [default: idem T file]
+  CHARACTER(LEN=256)                        :: cf_tfil              ! Temperature file for reference only
   CHARACTER(LEN=256)                        :: cf_ufil              ! zonal velocity file
   CHARACTER(LEN=256)                        :: cf_vfil              ! meridional velocity file
-  CHARACTER(LEN=256)                        :: cf_out='vt.nc'       ! output file
+  CHARACTER(LEN=256)                        :: cf_out='uv.nc'       ! output file
   CHARACTER(LEN=256)                        :: config               ! configuration name
   CHARACTER(LEN=256)                        :: ctag                 ! current tag to work with               
+  CHARACTER(LEN=256)                        :: cl_name              ! temporary variable name
 
   TYPE (variable), DIMENSION(4)             :: stypvar              ! structure for attributes
 
   LOGICAL                                   :: lcaltmean            ! flag for mean time computation
+  LOGICAL                                   :: lperio=.false.       ! flag for E-W periodicity
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
   !!  Read command line
   narg= iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfvT CONFIG-CASE ''list_of_tags'' '
+     PRINT *,' usage : cdfuv CONFIG-CASE ''list_of_tags'' '
      PRINT *,'     PURPOSE :'
-     PRINT *,'       Compute the time average values for second order products ' 
-     PRINT *,'       V.T, V.S, U.T and U.S used in heat and salt transport computation.'
+     PRINT *,'       Compute the time average values for U.V  product, at T point.' 
+     PRINT *,'       Mean U and V values at T points, and mean U''.V'' product are '
+     PRINT *,'       saved as well.'
      PRINT *,'      '
      PRINT *,'     ARGUMENTS :'
      PRINT *,'       CONFIG-CASE is the config name of a given experiment (eg ORCA025-G70)'
-     PRINT *,'            The program will look for gridT, gridU and gridV files for' 
-     PRINT *,'            this config ( grid_T, grid_U and grid_V are also accepted).'
-     PRINT *,'            Additionaly, if gridS or grid_S file is found, it will be taken'
-     PRINT *,'            in place of gridT for the salinity variable.'
+     PRINT *,'            The program will look for gridU and gridV files for' 
+     PRINT *,'            this config (grid_U and grid_V are also accepted).'
      PRINT *,'       list_of_tags : a list of time tags that will be used for time'
      PRINT *,'            averaging. e.g. y2000m01d05 y2000m01d10 ...'
      PRINT *,'      '
@@ -80,7 +81,10 @@ PROGRAM cdfvT
      PRINT *,'      '
      PRINT *,'     OUTPUT : '
      PRINT *,'       netcdf file : ', TRIM(cf_out) 
-     PRINT *,'       variables : ',TRIM(cn_vozout),', ',TRIM(cn_vozous),', ',TRIM(cn_vomevt),' and ',TRIM(cn_vomevs)
+     PRINT *,'       variables : ',TRIM(cn_vouv), '  : Mean U.V at T point'
+     PRINT *,'                   ',TRIM(cn_vozocrtx)//'_t : Mean U at T point'
+     PRINT *,'                   ',TRIM(cn_vomecrty)//'_t : Mean V at T point'
+     PRINT *,'                   ',TRIM(CN_VOUV)//'_prime : Mean U''.V'' at T point'
      STOP
   ENDIF
 
@@ -89,10 +93,15 @@ PROGRAM cdfvT
   CALL getarg (2, ctag  )
 
   cf_tfil = SetFileName( config, ctag, 'T')
+  cf_ufil = SetFileName( config, ctag, 'U')
+
+   
+
+  npiglo = getdim (cf_ufil,cn_x)
+  npjglo = getdim (cf_ufil,cn_y)
+  npk    = getdim (cf_ufil,cn_z)
+
 
-  npiglo = getdim (cf_tfil,cn_x)
-  npjglo = getdim (cf_tfil,cn_y)
-  npk    = getdim (cf_tfil,cn_z)
 
   ipk(:)= npk  ! all variables (input and output are 3D)
   ! define output variables
@@ -102,26 +111,41 @@ PROGRAM cdfvT
   stypvar%conline_operation = 'N/A'
   stypvar%caxis             = 'TZYX'
 
-  stypvar(1)%cname          = cn_vomevt       ; stypvar(1)%cunits        = 'm.DegC.s-1'
-  stypvar(2)%cname          = cn_vomevs       ; stypvar(2)%cunits        = 'm.PSU.s-1'
-  stypvar(3)%cname          = cn_vozout       ; stypvar(3)%cunits        = 'm.DegC.s-1'
-  stypvar(4)%cname          = cn_vozous       ; stypvar(4)%cunits        = 'm.PSU.s-1'
+  stypvar(1)%cname          = cn_vouv                  ; stypvar(1)%cunits        = 'm2/s2'
+  stypvar(1)%clong_name     = 'U.V product at T point' ; stypvar(1)%cshort_name   = cn_vouv
 
-  stypvar(1)%clong_name     = 'Meridional_VT' ; stypvar(1)%cshort_name   = cn_vomevt
-  stypvar(2)%clong_name     = 'Meridional_VS' ; stypvar(2)%cshort_name   = cn_vomevs
-  stypvar(3)%clong_name     = 'Zonal_UT'      ; stypvar(3)%cshort_name   = cn_vozout
-  stypvar(4)%clong_name     = 'Zonal_US'      ; stypvar(4)%cshort_name   = cn_vozous
+  cl_name = TRIM(cn_vozocrtx)//'_t'
+  stypvar(2)%cname          = cl_name                  ; stypvar(2)%cunits        = 'm/s'
+  stypvar(2)%clong_name     = 'Mean U at T point '     ; stypvar(2)%cshort_name   = cl_name
+
+  cl_name = TRIM(cn_vomecrty)//'_t'
+  stypvar(3)%cname          = cl_name                  ; stypvar(3)%cunits        = 'm/s'
+  stypvar(3)%clong_name     = 'Mean V at T point '     ; stypvar(3)%cshort_name   = cl_name
+
+  cl_name = TRIM(cn_vouv)//'_prime'
+  stypvar(4)%cname          = cl_name                     ; stypvar(3)%cunits        = 'm2/s2'
+  stypvar(4)%clong_name     = 'Uprime .Vprime at T point' ; stypvar(3)%cshort_name   = cl_name
 
   PRINT *, 'npiglo =', npiglo
   PRINT *, 'npjglo =', npjglo
   PRINT *, 'npk    =', npk
 
-  ALLOCATE( dcumulut(npiglo,npjglo), dcumulus(npiglo,npjglo) )
-  ALLOCATE( dcumulvt(npiglo,npjglo), dcumulvs(npiglo,npjglo) )
-  ALLOCATE( zu(npiglo,npjglo),    zv(npiglo,npjglo) )
-  ALLOCATE( zworku(npiglo,npjglo),   zworkv(npiglo,npjglo) )
-  ALLOCATE( ztemp(npiglo,npjglo),    zsal(npiglo,npjglo) )
+  ALLOCATE( dcumuluv(npiglo,npjglo) )
+  ALLOCATE( dcumulu(npiglo,npjglo) )
+  ALLOCATE( dcumulv(npiglo,npjglo) )
+  ALLOCATE( dupvp(npiglo,npjglo) )
+  ALLOCATE( zu(npiglo,npjglo),     zv(npiglo,npjglo) )
+  ALLOCATE( zworku(npiglo,npjglo), zworkv(npiglo,npjglo) )
   ALLOCATE( zmean(npiglo,npjglo))
+  ALLOCATE( zlon(npiglo,npjglo))
+
+   ! check for E_W periodicity
+
+  zlon(:,:) = getvar(cf_tfil, cn_vlon2d, 1, npiglo, npjglo )
+  IF ( zlon(1,1) ==  zlon(npiglo-1,1) ) THEN
+     lperio = .TRUE.
+     PRINT *,' E-W periodicity detected '
+  ENDIF
 
   ! create output fileset
   ncout = create      (cf_out, cf_tfil, npiglo, npjglo, npk, ld_xycoo=.TRUE. )
@@ -131,20 +155,17 @@ PROGRAM cdfvT
   lcaltmean=.TRUE.
   DO jk = 1, npk
      PRINT *,'level ',jk
-     dcumulut(:,:) = 0.d0 ;  dcumulvt(:,:) = 0.d0 ; dtotal_time = 0.d0
-     dcumulus(:,:) = 0.d0 ;  dcumulvs(:,:) = 0.d0 ; ntframe = 0
+     dcumuluv(:,:) = 0.d0 ;  dtotal_time  = 0.d0 ; ntframe = 0
+     dcumulu(:,:)  = 0.d0 ;  dcumulv(:,:) = 0.d0
 
      DO jt = 2, narg           ! loop on tags
         CALL getarg (jt, ctag)
 
-        cf_tfil = SetFileName( config, ctag, 'T', ld_stop=.TRUE. )
-        cf_sfil = SetFileName( config, ctag, 'S', ld_stop=.FALSE.)      ! do not stop if gridS/grid_S not found !
-        IF ( chkfile (cf_sfil, ld_verbose=.FALSE.) ) cf_sfil = cf_tfil  ! do not complain if not found
-
-        npt = getdim (cf_tfil, cn_t)
+        cf_ufil = SetFileName( config, ctag, 'U', ld_stop=.TRUE. )
+        npt = getdim (cf_ufil, cn_t)
         IF ( lcaltmean ) THEN
            ALLOCATE ( tim(npt) )
-           tim = getvar1d(cf_tfil, cn_vtimec, npt)
+           tim = getvar1d(cf_ufil, cn_vtimec, npt)
            dtotal_time = dtotal_time + SUM(tim(1:npt) )
            DEALLOCATE( tim )
         END IF
@@ -157,46 +178,43 @@ PROGRAM cdfvT
            ntframe = ntframe+1
            zu(:,:)    = getvar(cf_ufil, cn_vozocrtx, jk, npiglo, npjglo, ktime=jtt )
            zv(:,:)    = getvar(cf_vfil, cn_vomecrty, jk, npiglo, npjglo, ktime=jtt )
-           ztemp(:,:) = getvar(cf_tfil, cn_votemper, jk, npiglo, npjglo, ktime=jtt )
-           zsal(:,:)  = getvar(cf_sfil, cn_vosaline, jk, npiglo, npjglo, ktime=jtt )
 
-           ! temperature at u point, v points
+           ! U and V velocities at T point
            zworku(:,:) = 0. ; zworkv(:,:) = 0.
-           DO ji=1, npiglo-1
-              DO jj = 1, npjglo -1
-                 zworku(ji,jj) = 0.5 * ( ztemp(ji,jj) + ztemp(ji+1,jj) )  ! temper at Upoint
-                 zworkv(ji,jj) = 0.5 * ( ztemp(ji,jj) + ztemp(ji,jj+1) )  ! temper at Vpoint
+           DO ji=2, npiglo
+              DO jj = 1, npjglo
+                 zworku(ji,jj) = 0.5 * ( zu(ji,jj) + zu(ji-1,jj) )  ! U at T point
               END DO
            END DO
 
-           dcumulut(:,:) = dcumulut(:,:) + zworku(:,:) * zu(:,:)*1.d0
-           dcumulvt(:,:) = dcumulvt(:,:) + zworkv(:,:) * zv(:,:)*1.d0
-
-           ! salinity at u points, v points
-           zworku(:,:) = 0. ; zworkv(:,:) = 0.
-           DO ji=1, npiglo-1
-              DO jj = 1, npjglo -1
-                 zworku(ji,jj) = 0.5 * ( zsal(ji,jj) + zsal(ji+1,jj) )  ! salinity  at Upoint
-                 zworkv(ji,jj) = 0.5 * ( zsal(ji,jj) + zsal(ji,jj+1) )  ! salinity  at Vpoint
+           DO ji=1, npiglo
+              DO jj = 2, npjglo 
+                 zworkv(ji,jj) = 0.5 * ( zv(ji,jj) + zv(ji,jj-1) )  ! V at T point
               END DO
            END DO
 
-           dcumulus(:,:) = dcumulus(:,:) + zworku(:,:) * zu(:,:)*1.d0
-           dcumulvs(:,:) = dcumulvs(:,:) + zworkv(:,:) * zv(:,:)*1.d0
+           dcumuluv(:,:) = dcumuluv(:,:) + zworku(:,:) * zworkv(:,:)*1.d0
+           dcumulu(:,:)  = dcumulu(:,:)  + zworku(:,:)*1.d0
+           dcumulv(:,:)  = dcumulv(:,:)  + zworkv(:,:)*1.d0
 
         END DO  !jtt
      END DO  ! jt
      ! finish with level jk ; compute mean (assume spval is 0 )
-     zmean(:,:) = dcumulvt(:,:)/ntframe
+     zmean(:,:) = dcumuluv(:,:)/ntframe
+     IF ( lperio ) zmean(1, :) = zmean(npiglo-1,:)
      ierr = putvar(ncout, id_varout(1), zmean, jk,npiglo, npjglo, kwght=ntframe )
 
-     zmean(:,:) = dcumulvs(:,:)/ntframe
+     zmean(:,:) = dcumulu(:,:)/ntframe
+     IF ( lperio ) zmean(1, :) = zmean(npiglo-1,:)
      ierr = putvar(ncout, id_varout(2), zmean, jk,npiglo, npjglo, kwght=ntframe )
 
-     zmean(:,:) = dcumulut(:,:)/ntframe
+     zmean(:,:) = dcumulv(:,:)/ntframe
+     IF ( lperio ) zmean(1, :) = zmean(npiglo-1,:)
      ierr = putvar(ncout, id_varout(3), zmean, jk,npiglo, npjglo, kwght=ntframe )
 
-     zmean(:,:) = dcumulus(:,:)/ntframe
+     dupvp(:,:) = dcumuluv(:,:)/ntframe - dcumulu(:,:)*dcumulv(:,:)/ntframe/ntframe
+     zmean(:,:) = dupvp(:,:)
+     IF ( lperio ) zmean(1, :) = zmean(npiglo-1,:)
      ierr = putvar(ncout, id_varout(4), zmean, jk,npiglo, npjglo, kwght=ntframe )
 
      IF (lcaltmean )  THEN
@@ -209,4 +227,4 @@ PROGRAM cdfvT
 
   ierr = closeout(ncout)
 
-END PROGRAM cdfvT
+END PROGRAM cdfuv
diff --git a/cdfvFWov.f90 b/src/cdfvFWov.f90
similarity index 100%
rename from cdfvFWov.f90
rename to src/cdfvFWov.f90
diff --git a/cdfvT.f90 b/src/cdfvT.f90
similarity index 82%
rename from cdfvT.f90
rename to src/cdfvT.f90
index 7e97310..4b5b054 100644
--- a/cdfvT.f90
+++ b/src/cdfvT.f90
@@ -24,9 +24,10 @@ PROGRAM cdfvT
   !!----------------------------------------------------------------------
   IMPLICIT NONE
 
-  INTEGER(KIND=4)                           :: ji, jj, jk, jt, jtt  ! dummy loop index
+  INTEGER(KIND=4)                           :: ji, jj, jk, jv, jtt  ! dummy loop index
   INTEGER(KIND=4)                           :: ierr                 ! working integer
-  INTEGER(KIND=4)                           :: narg, iargc          ! command line
+  INTEGER(KIND=4)                           :: narg, iargc, n1      ! command line
+  INTEGER(KIND=4)                           :: ijarg, ixtra         ! command line
   INTEGER(KIND=4)                           :: npiglo,npjglo        ! size of the domain
   INTEGER(KIND=4)                           :: npk, npt             ! size of the domain
   INTEGER(KIND=4)                           :: ntframe              ! Cumul of time frame
@@ -51,17 +52,19 @@ PROGRAM cdfvT
   CHARACTER(LEN=256)                        :: cf_out='vt.nc'       ! output file
   CHARACTER(LEN=256)                        :: config               ! configuration name
   CHARACTER(LEN=256)                        :: ctag                 ! current tag to work with               
+  CHARACTER(LEN=256)                        :: cldum                ! dummy character argument
 
   TYPE (variable), DIMENSION(4)             :: stypvar              ! structure for attributes
 
   LOGICAL                                   :: lcaltmean            ! flag for mean time computation
+  LOGICAL                                   :: lnc4=.false.         ! flag for netcdf4 output with chunking and deflation
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
   !!  Read command line
   narg= iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfvT CONFIG-CASE ''list_of_tags'' '
+     PRINT *,' usage : cdfvT CONFIG-CASE [-o output_file ] [-nc4 ] ''list_of_tags'' '
      PRINT *,'     PURPOSE :'
      PRINT *,'       Compute the time average values for second order products ' 
      PRINT *,'       V.T, V.S, U.T and U.S used in heat and salt transport computation.'
@@ -72,6 +75,8 @@ PROGRAM cdfvT
      PRINT *,'            this config ( grid_T, grid_U and grid_V are also accepted).'
      PRINT *,'            Additionaly, if gridS or grid_S file is found, it will be taken'
      PRINT *,'            in place of gridT for the salinity variable.'
+     PRINT *,'       [-nc4 ] use netcdf4 output with chunking and deflation 1'
+     PRINT *,'       [-o output file ] default :',TRIM(cf_out),'  must be before tag list'
      PRINT *,'       list_of_tags : a list of time tags that will be used for time'
      PRINT *,'            averaging. e.g. y2000m01d05 y2000m01d10 ...'
      PRINT *,'      '
@@ -85,8 +90,24 @@ PROGRAM cdfvT
   ENDIF
 
   !! Initialisation from 1st file (all file are assume to have the same geometry)
-  CALL getarg (1, config)
-  CALL getarg (2, ctag  )
+  ijarg = 1 ; n1 = 2 ; ixtra=1
+  DO WHILE ( ijarg <= narg ) 
+    CALL getarg (ijarg, cldum ) ; ijarg = ijarg + 1
+    SELECT CASE ( cldum ) 
+    CASE ( '-o' )
+      CALL getarg (ijarg, cf_out) ; ijarg = ijarg + 1
+      n1 = n1 + 2
+    CASE ( '-nc4' )
+      lnc4 = .true.
+      n1 = n1 + 1
+    CASE DEFAULT
+      IF ( ixtra == 1 ) THEN   ! first argument w/o options is config
+         config=cldum ; ixtra = ixtra + 1
+      ELSE IF ( ixtra == 2 ) THEN ! all other extra arguments are tags. keep the first, now
+         ctag=cldum
+      ENDIF
+     END SELECT
+  ENDDO
 
   cf_tfil = SetFileName( config, ctag, 'T')
 
@@ -101,6 +122,9 @@ PROGRAM cdfvT
   stypvar%valid_max         = 100.
   stypvar%conline_operation = 'N/A'
   stypvar%caxis             = 'TZYX'
+  DO jv = 1, 4
+     stypvar(jv)%ichunk = (/npiglo,MAX(1,npjglo/30), 1, 1 /)
+  ENDDO
 
   stypvar(1)%cname          = cn_vomevt       ; stypvar(1)%cunits        = 'm.DegC.s-1'
   stypvar(2)%cname          = cn_vomevs       ; stypvar(2)%cunits        = 'm.PSU.s-1'
@@ -124,8 +148,8 @@ PROGRAM cdfvT
   ALLOCATE( zmean(npiglo,npjglo))
 
   ! create output fileset
-  ncout = create      (cf_out, cf_tfil, npiglo, npjglo, npk, ld_xycoo=.TRUE. )
-  ierr  = createvar   (ncout , stypvar, 4,      ipk,    id_varout            )
+  ncout = create      (cf_out, cf_tfil, npiglo, npjglo, npk, ld_xycoo=.TRUE. , ld_nc4=lnc4 )
+  ierr  = createvar   (ncout , stypvar, 4,      ipk,    id_varout            , ld_nc4=lnc4 )
   ierr  = putheadervar(ncout,  cf_tfil, npiglo, npjglo, npk, ld_xycoo=.TRUE. )
   
   lcaltmean=.TRUE.
@@ -134,8 +158,24 @@ PROGRAM cdfvT
      dcumulut(:,:) = 0.d0 ;  dcumulvt(:,:) = 0.d0 ; dtotal_time = 0.d0
      dcumulus(:,:) = 0.d0 ;  dcumulvs(:,:) = 0.d0 ; ntframe = 0
 
-     DO jt = 2, narg           ! loop on tags
-        CALL getarg (jt, ctag)
+     ijarg = 1 ; ixtra=1 ; ctag='none'
+     DO WHILE ( ijarg <= narg ) 
+          CALL getarg (ijarg, cldum ) ; ijarg = ijarg + 1
+
+          SELECT CASE ( cldum ) 
+          CASE ( '-o' )
+            CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1
+            CYCLE
+          CASE ( '-nc4' )
+             CYCLE
+          CASE DEFAULT
+             IF ( ixtra == 1 ) THEN   ! first argument w/o options is config
+                ixtra = ixtra + 1 
+                CYCLE
+             ELSE IF ( ixtra > 1 ) THEN ! all other extra arguments are tags. keep the first, now
+                ctag=cldum  ! process this tag !
+             ENDIF
+          END SELECT
 
         cf_tfil = SetFileName( config, ctag, 'T', ld_stop=.TRUE. )
         cf_sfil = SetFileName( config, ctag, 'S', ld_stop=.FALSE.)      ! do not stop if gridS/grid_S not found !
@@ -185,7 +225,7 @@ PROGRAM cdfvT
            dcumulvs(:,:) = dcumulvs(:,:) + zworkv(:,:) * zv(:,:)*1.d0
 
         END DO  !jtt
-     END DO  ! jt
+     END DO  ! arg list
      ! finish with level jk ; compute mean (assume spval is 0 )
      zmean(:,:) = dcumulvt(:,:)/ntframe
      ierr = putvar(ncout, id_varout(1), zmean, jk,npiglo, npjglo, kwght=ntframe )
diff --git a/cdfvertmean.f90 b/src/cdfvertmean.f90
similarity index 53%
rename from cdfvertmean.f90
rename to src/cdfvertmean.f90
index 6c917a1..1feb370 100644
--- a/cdfvertmean.f90
+++ b/src/cdfvertmean.f90
@@ -10,6 +10,7 @@ PROGRAM cdfvertmean
   !!
   !! History : 2.1  : 11/2008  : J.M. Molines : Original code
   !!           3.0  : 01/2011  : J.M. Molines : Doctor norm + Lic.
+  !!           3.0  : 06/2013  : J.M. Molines : multi variables capability
   !!----------------------------------------------------------------------
   USE cdfio
   USE modcdfnames
@@ -22,15 +23,16 @@ PROGRAM cdfvertmean
   !!----------------------------------------------------------------------
   IMPLICIT NONE
 
-  INTEGER(KIND=4)                               :: jk, jvar, jt        ! dummy loop index
+  INTEGER(KIND=4)                               :: jk, jvar, jvarin, jt! dummy loop index
   INTEGER(KIND=4)                               :: ik1, ik2            ! vertical limit of integration
   INTEGER(KIND=4)                               :: narg, iargc         ! command line 
   INTEGER(KIND=4)                               :: ijarg, ireq         ! command line 
   INTEGER(KIND=4)                               :: npiglo, npjglo      ! size of the domain
   INTEGER(KIND=4)                               :: npk, npt            ! size of the domain,
   INTEGER(KIND=4)                               :: nvars, ivar         ! variables in input
+  INTEGER(KIND=4)                               :: nvaro=1             ! variables for output
   INTEGER(KIND=4)                               :: ncout, ierr         ! ncid and error status
-  INTEGER(KIND=4), DIMENSION(1)                 :: ipk, id_varout      ! levels and varid's of output vars
+  INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: ipk, id_varout      ! levels and varid's of output vars
 
   REAL(KIND=4)                                  :: rdep_up             ! upper level of integration
   REAL(KIND=4)                                  :: rdep_down           ! lower level of integration
@@ -49,8 +51,7 @@ PROGRAM cdfvertmean
 
   CHARACTER(LEN=256)                            :: cf_in               ! input file name
   CHARACTER(LEN=256)                            :: cf_out='vertmean.nc'! output file
-  CHARACTER(LEN=256)                            :: cv_in               ! variable name
-  CHARACTER(LEN=256)                            :: cv_out='sovertmean' ! variable name
+  CHARACTER(LEN=256)                            :: cv_cur              ! variable name
   CHARACTER(LEN=256)                            :: cv_dep              ! depth name
   CHARACTER(LEN=256)                            :: cv_e3               ! vertical metric name (partial)
   CHARACTER(LEN=256)                            :: cv_e31d             ! vertical metric name (full)
@@ -59,18 +60,21 @@ PROGRAM cdfvertmean
   CHARACTER(LEN=256)                            :: cglobal             ! global attribute
   CHARACTER(LEN=256)                            :: cldum               ! dummy string
   CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_names            ! name of input variables
- 
+  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_in               ! name of output variables
+
   TYPE(variable), DIMENSION(:), ALLOCATABLE     :: stypvarin           ! stucture for attributes (input)
-  TYPE(variable), DIMENSION(1)                  :: stypvar             ! stucture for attributes (output)
+  TYPE(variable), DIMENSION(:), ALLOCATABLE     :: stypvar             ! stucture for attributes (output)
 
-  LOGICAL                                       :: lfull=.FALSE.       ! full step flag
+  LOGICAL                                       :: lfull =.FALSE.      ! full step flag
+  LOGICAL                                       :: ldebug=.FALSE.      ! full step flag
   LOGICAL                                       :: lchk                ! file existence flag (true if missing)
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
   narg = iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage :  cdfvertmean IN-file IN-var v-type dep1 dep2 [-full]'
+     PRINT *,' usage :  cdfvertmean [-debug] IN-file IN-var1,var2,.. v-type dep1 dep2 [-full]'
+     PRINT *,'              ... [-o OUT-file ]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
      PRINT *,'       Compute the vertical mean between dep1 and dep2 given in m,'
@@ -78,40 +82,45 @@ PROGRAM cdfvertmean
      PRINT *,'      '
      PRINT *,'     ARGUMENTS :'
      PRINT *,'       IN-file  : netcdf input file.' 
-     PRINT *,'       IN-var   : netcdf input variable.'
+     PRINT *,'       IN-var1,var2,.. : Comma separated list of input variables to process.'
      PRINT *,'       v-type   : one of T U V W indicating position of variable on C-grid'
-     PRINT *,'       dep1 dep2 : depths limit for vertical integration (meters). '
+     PRINT *,'       dep1 dep2 : depths limit for vertical integration (meters), from top '
+     PRINT *,'                to bottom, positive depths.'
      PRINT *,'      '
      PRINT *,'     OPTIONS :'
-     PRINT *,'       [-full ] : for full step configurations. Default is partial step.'
+     PRINT *,'       [-full  ] : for full step configurations. Default is partial step.'
+     PRINT *,'       [-debug ] : print some extra informations.'
+     PRINT *,'       [-o OUT-file ] : specify output file instead of ',TRIM(cf_out)
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'       ', TRIM(cn_fzgr),' and ',TRIM(cn_fmsk)
      PRINT *,'      '
      PRINT *,'     OUTPUT : '
      PRINT *,'       netcdf file : ', TRIM(cf_out) 
-     PRINT *,'         variables : ', TRIM(cv_out),' (same units as input variable)'
+     PRINT *,'         variables : varin_vertmean (same units as input variable)'
      PRINT *,'      '
      STOP
   ENDIF
 
   ijarg = 1 ; ireq=0
   DO WHILE ( ijarg <= narg ) 
-    CALL getarg (ijarg, cldum ) ; ijarg = ijarg + 1
-    SELECT CASE ( cldum )
-    CASE ( '-full' ) ; lfull = .TRUE.
-    CASE DEFAULT
-       ireq=ireq+1
-       SELECT CASE ( ireq )
-       CASE ( 1 ) ; cf_in=cldum
-       CASE ( 2 ) ; cv_in=cldum
-       CASE ( 3 ) ; ctype=cldum
-       CASE ( 4 ) ; READ(cldum,*) rdep_up
-       CASE ( 5 ) ; READ(cldum,*) rdep_down
-       CASE DEFAULT
-          PRINT *,' Too many arguments ...' ; STOP
-       END SELECT
-    END SELECT
+     CALL getarg (ijarg, cldum ) ; ijarg = ijarg + 1
+     SELECT CASE ( cldum )
+     CASE ( '-full'  ) ; lfull  = .TRUE.
+     CASE ( '-debug' ) ; ldebug = .TRUE.
+     CASE ( '-o' )     ; CALL getarg (ijarg, cf_out ) ; ijarg = ijarg + 1
+     CASE DEFAULT
+        ireq=ireq+1
+        SELECT CASE ( ireq )
+        CASE ( 1 ) ; cf_in=cldum
+        CASE ( 2 ) ; CALL ParseVars(cldum)
+        CASE ( 3 ) ; ctype=cldum
+        CASE ( 4 ) ; READ(cldum,*) rdep_up
+        CASE ( 5 ) ; READ(cldum,*) rdep_down
+        CASE DEFAULT
+           PRINT *,' Too many arguments ...' ; STOP
+        END SELECT
+     END SELECT
   ENDDO
 
   lchk = chkfile (cn_fzgr)
@@ -131,58 +140,58 @@ PROGRAM cdfvertmean
   npk    = getdim (cf_in,cn_z)
   npt    = getdim (cf_in,cn_t)
 
-  nvars       = getnvar(cf_in)
-  ALLOCATE( cv_names(nvars), stypvarin(nvars) )
-  cv_names(:) = getvarname(cf_in, nvars, stypvarin)
-  ivar=1
-  DO jvar=1,nvars
-     IF ( TRIM(cv_names(jvar)) == TRIM(cv_in) ) THEN
-        EXIT
-     ENDIF
-     ivar=ivar+1
-  ENDDO
-
-  IF ( ivar == nvars+1 ) THEN
-     PRINT *,' Variable ',TRIM(cv_in),' not found in ', TRIM(cf_in)
-     STOP
-  ENDIF
-
-  rdep(1)                      = 0.
-  ipk(:)                       = 1
-  stypvar(1)%cname             = cv_out
-  stypvar(1)%cunits            = stypvarin(ivar)%cunits
-  stypvar(1)%rmissing_value    = stypvarin(ivar)%rmissing_value
-  stypvar(1)%valid_min         = stypvarin(ivar)%valid_min
-  stypvar(1)%valid_max         = stypvarin(ivar)%valid_max
-  stypvar(1)%clong_name        = 'vertical average of '//TRIM(stypvarin(ivar)%clong_name)
-  stypvar(1)%cshort_name       = cv_out
-  stypvar(1)%conline_operation = 'N/A'
-  stypvar(1)%caxis             = 'TYX'
-
   PRINT *, 'npiglo = ', npiglo
   PRINT *, 'npjglo = ', npjglo
   PRINT *, 'npk    = ', npk
   PRINT *, 'npt    = ', npt
 
+  nvars       = getnvar(cf_in)
+  ALLOCATE( cv_names(nvars), stypvarin(nvars) )
+  ALLOCATE( stypvar(nvaro), ipk(nvaro), id_varout(nvaro) )
+  cv_names(:) = getvarname(cf_in, nvars, stypvarin)
+
+  ! just chck if var exist in file 
+  DO jvar = 1, nvaro
+     IF ( chkvar( cf_in, cv_in(jvar)) ) STOP  ! message is written in cdfio.chkvar
+  ENDDO
+
   ! Allocate arrays
   ALLOCATE ( zmask(npiglo,npjglo), dvertmean(npiglo, npjglo) )
   ALLOCATE ( zv(npiglo,npjglo), hdep(npiglo,npjglo)          )
   ALLOCATE ( e3(npiglo,npjglo), dvol2d(npiglo,npjglo)        )
   ALLOCATE ( gdep(npk), tim(npt)                             )
-
   IF ( lfull ) ALLOCATE ( e31d(npk) )
 
+  rdep(1)                      = 0.
+  ipk(:)                       = 1
+  DO jvar=1, nvaro
+     DO jvarin=1,nvars
+        IF ( cv_in(jvar) == stypvarin(jvarin)%cname ) EXIT  ! cv_in match cv_varin.
+     END DO
+     stypvar(jvar)%cname             = TRIM(cv_in(jvar))//'_vert_mean'
+     stypvar(jvar)%cunits            = stypvarin(jvarin)%cunits
+     stypvar(jvar)%rmissing_value    = stypvarin(jvarin)%rmissing_value
+     stypvar(jvar)%valid_min         = stypvarin(jvarin)%valid_min
+     stypvar(jvar)%valid_max         = stypvarin(jvarin)%valid_max
+     stypvar(jvar)%clong_name        = 'vertical average of '//TRIM(stypvarin(jvarin)%clong_name)
+     stypvar(jvar)%cshort_name       = TRIM(cv_in(jvar))//'_vert_mean'
+     stypvar(jvar)%conline_operation = 'N/A'
+     stypvar(jvar)%caxis             = 'TYX'
+  END DO
+
   ! Initialize output file
   ncout = create      (cf_out, cf_in,   npiglo, npjglo, 1)
-  ierr  = createvar   (ncout,  stypvar, 1,      ipk,    id_varout, cdglobal=cglobal  )
+  ierr  = createvar   (ncout,  stypvar, nvaro,  ipk,    id_varout, cdglobal=cglobal  )
   ierr  = putheadervar(ncout,  cf_in,   npiglo, npjglo, 1, pdep=rdep)
 
   tim  = getvar1d(cf_in, cn_vtimec, npt     )
   ierr = putvar1d(ncout, tim,       npt, 'T')
 
   SELECT CASE ( ctype)
-  CASE( 'T','U','V','t','u','v');  cv_dep=cn_gdepw ; cv_e3='e3t_ps' ; cv_e31d=cn_ve3t 
-  CASE( 'W' ,'w')               ;  cv_dep=cn_gdept ; cv_e3='e3w_ps' ; cv_e31d=cn_ve3w
+  CASE( 'T','t');  cv_dep=cn_gdepw ; cv_e3='e3t_ps' ; cv_e31d=cn_ve3t 
+  CASE( 'U','u');  cv_dep=cn_gdepw ; cv_e3='e3u_ps' ; cv_e31d=cn_ve3t 
+  CASE( 'V','v');  cv_dep=cn_gdepw ; cv_e3='e3v_ps' ; cv_e31d=cn_ve3t 
+  CASE( 'W','w');  cv_dep=cn_gdept ; cv_e3='e3w_ps' ; cv_e31d=cn_ve3w
   CASE DEFAULT ; PRINT *,'Point type ', TRIM(ctype),' not known! ' ; STOP
   END SELECT
 
@@ -203,49 +212,91 @@ PROGRAM cdfvertmean
      IF ( gdep(jk) <= rdep_down ) ik2 = jk
   ENDDO
 
-  PRINT '(a,2f8.3)', 'depth limit of integration : ', rdep_up, rdep_down
-  PRINT '(a,2i8  )', 'nearest level found        : ', ik1,     ik2
-  PRINT '(a,2f8.3)', 'corresponding depth        : ', gdep(ik1), gdep(ik2+1)
+  PRINT '(a,2f10.3)', 'depth limit of integration : ', rdep_up, rdep_down
+  PRINT '(a,2i10  )', 'nearest level found        : ', ik1,     ik2
+  PRINT '(a,2f10.3)', 'corresponding depth        : ', gdep(ik1), gdep(MIN(ik2+1,npk))
 
   DO jt=1,npt
-     dvol           = 0.d0
-     dvol2d(:,:)    = 0.d0
-     dvertmean(:,:) = 0.d0
-
-     DO jk = ik1, ik2
-        ! Get values at jk
-        zv(   :,:) = getvar(cf_in,   cv_in,  jk, npiglo, npjglo, ktime=jt)
-        zmask(:,:) = getvar(cn_fmsk, cv_msk, jk, npiglo, npjglo          )
-
-        ! get e3 at level jk ( ps...)
-        IF ( lfull ) THEN ; e3(:,:) = e31d(jk)
-        ELSE              ; e3(:,:) = getvar(cn_fzgr, cv_e3, jk, npiglo, npjglo, ldiom=.TRUE.)
-        ENDIF
-
-        IF ( jk == ik1 ) THEN
-           hdep(:,:) = gdep(jk) + e3(:,:)
-           e3(  :,:) = MIN(e3, hdep -rdep_up          )
-        ENDIF
-
-        IF ( jk == ik2 ) THEN
-           e3(  :,:) = MIN(e3, (rdep_down) - gdep(jk) )
-        ENDIF
-
-        dvol       = SUM( DBLE(e3 * zmask) )
-        dvol2d     =      e3 * zmask * 1.d0  + dvol2d
-        dvertmean  = zv * e3 * zmask * 1.d0  + dvertmean
-
-        IF (dvol == 0 )THEN
-                  ! no more layer below !    
-           EXIT   ! get out of the jk loop
-        ENDIF
+     DO jvar = 1,nvaro
+        cv_cur = cv_in(jvar)
+        dvol           = 0.d0
+        dvol2d(:,:)    = 0.d0
+        dvertmean(:,:) = 0.d0
+
+        DO jk = ik1, ik2
+           ! Get values at jk
+           zv(   :,:) = getvar(cf_in,   cv_cur, jk, npiglo, npjglo, ktime=jt)
+           zmask(:,:) = getvar(cn_fmsk, cv_msk, jk, npiglo, npjglo          )
+
+           ! get e3 at level jk ( ps...)
+           IF ( lfull ) THEN ; e3(:,:) = e31d(jk)
+           ELSE              ; e3(:,:) = getvar(cn_fzgr, cv_e3, jk, npiglo, npjglo, ldiom=.TRUE.)
+           ENDIF
+
+           IF ( jk == ik1 ) THEN
+              hdep(:,:) = gdep(jk) + e3(:,:)
+              e3(  :,:) = MIN(e3, hdep -rdep_up          )
+           ENDIF
+
+           IF ( jk == ik2 ) THEN
+              e3(  :,:) = MIN(e3, (rdep_down) - gdep(jk) )
+           ENDIF
+
+           dvol       = SUM( DBLE(e3 * zmask) )
+           dvol2d     =      e3 * zmask * 1.d0  + dvol2d
+           dvertmean  = zv * e3 * zmask * 1.d0  + dvertmean
+
+           IF (dvol == 0 )THEN
+              ! no more layer below !    
+              EXIT   ! get out of the jk loop
+           ENDIF
+        END DO
+
+        ! Output to netcdf file 
+        WHERE ( dvol2d /= 0 )  dvertmean = dvertmean/dvol2d
+        ierr = putvar(ncout, id_varout(jvar), REAL(dvertmean), 1, npiglo, npjglo, ktime=jt)
      END DO
-
-     ! Output to netcdf file 
-     WHERE ( dvol2d /= 0 )  dvertmean = dvertmean/dvol2d
-     ierr = putvar(ncout, id_varout(1), REAL(dvertmean), 1, npiglo, npjglo, ktime=jt)
   END DO  ! loop on time
 
   ierr = closeout(ncout)
+CONTAINS
+  SUBROUTINE ParseVars (cdum)
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE ParseVars  ***
+    !!
+    !! ** Purpose :  Decode variable name  option from command line
+    !!
+    !! ** Method  :  look for , in the argument string and set the number of
+    !!         variable (nvaro), allocate cv_in array and fill it with the
+    !!         decoded  names.
+    !!
+    !!----------------------------------------------------------------------
+    CHARACTER(LEN=*), INTENT(in) :: cdum
+
+    CHARACTER(LEN=80), DIMENSION(100) :: cl_dum  ! 100 is arbitrary
+    INTEGER  :: ji
+    INTEGER  :: inchar,  i1=1
+    !!----------------------------------------------------------------------
+    inchar= LEN(TRIM(cdum))
+    ! scan the input string and look for ',' as separator
+    DO ji=1,inchar
+       IF ( cdum(ji:ji) == ',' ) THEN
+          cl_dum(nvaro) = cdum(i1:ji-1)
+          i1=ji+1
+          nvaro=nvaro+1
+       ENDIF
+    ENDDO
+
+    ! last name of the list does not have a ','
+    cl_dum(nvaro) = cdum(i1:inchar)
+
+    ALLOCATE ( cv_in(nvaro) )
+    IF ( ldebug) PRINT *,' SELECTED VARIABLES :'
+    DO ji=1, nvaro
+       cv_in(ji) = cl_dum(ji)
+       IF ( ldebug) PRINT *, "    ",TRIM(cv_in(ji))
+    ENDDO
+  END SUBROUTINE ParseVars
+
 
 END PROGRAM cdfvertmean
diff --git a/cdfvhst.f90 b/src/cdfvhst.f90
similarity index 100%
rename from cdfvhst.f90
rename to src/cdfvhst.f90
diff --git a/cdfvint.f90 b/src/cdfvint.f90
similarity index 70%
rename from cdfvint.f90
rename to src/cdfvint.f90
index bccede6..f9079f1 100644
--- a/cdfvint.f90
+++ b/src/cdfvint.f90
@@ -11,6 +11,7 @@ PROGRAM cdfvint
    !!
    !! History : 2.1  : 10/2012  : M.A. Balmaseda : Original code from cdfmxlhc
    !!           3.0  : 11/2012  : J.M. Molines   : Doctor norm + Lic + ...
+   !!                  02/2016  : S. Leroux      : Add -OCCI option
    !!----------------------------------------------------------------------
    USE cdfio
    USE modcdfnames
@@ -53,8 +54,13 @@ PROGRAM cdfvint
 
    LOGICAL                                   :: lfull =.FALSE.      ! flag for full step computation
    LOGICAL                                   :: lgsop =.FALSE.      ! selected depths gsop intercomparison
+   LOGICAL                                   :: locci =.FALSE.      ! selected 3 depths for occiput 
    LOGICAL                                   :: lchk  =.FALSE.      ! flag for missing files
    LOGICAL                                   :: lout                ! check for output
+   LOGICAL                                   :: lnc4  =.FALSE.      ! flag for netcdf4 chunking and deflation
+   LOGICAL                                   :: ltmean=.FALSE.      ! flag for mean temperature output
+   LOGICAL                                   :: lsmean=.FALSE.      ! flag for mean salinity output
+   LOGICAL                                   :: lfout =.FALSE.      ! flag for output filename
 
    TYPE(variable), DIMENSION(1)              :: stypvar             ! extension for attributes
    !!----------------------------------------------------------------------
@@ -62,31 +68,40 @@ PROGRAM cdfvint
 
    narg= iargc()
    IF ( narg == 0 ) THEN
-      PRINT *,' usage : cdfvint T-file [IN-var] [-GSOP] [-full] '
+      PRINT *,' usage : cdfvint T-file [IN-var] [-GSOP] [-OCCI] [-full] [-nc4] [-o OUT-file]'
+      PRINT *,'                 [-tmean] [-smean]'
       PRINT *,'      '
       PRINT *,'     PURPOSE :'
       PRINT *,'          Compute the vertical integral of the variable from top '
       PRINT *,'       to bottom, and save the cumulated valued, level by level.'
       PRINT *,'       For temperature (default var), the integral is transformed'
-      PRINT *,'       to Heat Content ( J.K. m^-2) hence for salinity, the integral'
+      PRINT *,'       to Heat Content ( 10^6 J/m2) hence for salinity, the integral'
       PRINT *,'       represents PSU.m '
       PRINT *,'      '
       PRINT *,'     ARGUMENTS :'
-      PRINT *,'         T-file : gridT file holding either Temperature or salinity '
+      PRINT *,'         T-file : gridT file holding either temperature or salinity '
       PRINT *,'        [IN-var ] : name of input variable to process. Default is '
       PRINT *,'               ', TRIM(cn_votemper),'. Can also be ',TRIM(cn_vosaline)
       PRINT *,'      '
       PRINT *,'     OPTIONS :'
       PRINT *,'        -GSOP : Use 7 GSOP standard level for the output '
       PRINT *,'                Default is to take the model levels for the output'
+      PRINT *,'        -OCCI : Use 3 levels for the output: 700m, 2000m and bottom'
+      PRINT *,'                Default is to take the model levels for the output'
       PRINT *,'        -full : for full step computation ' 
+      PRINT *,'        -nc4  : use netcdf4 output with chunking and deflation'
+      PRINT *,'        -tmean : output mean temperature instead of heat content'
+      PRINT *,'        -smean : output mean salinity instead of PSU.m'
+      PRINT *,'        -o OUT-file : use specified output file instead of <IN-var>.nc'
       PRINT *,'      '
       PRINT *,'     REQUIRED FILES :'
       PRINT *,'       ', TRIM(cn_fmsk),', ',TRIM(cn_fhgr),' and ', TRIM(cn_fzgr) 
       PRINT *,'      '
       PRINT *,'     OUTPUT : '
-      PRINT *,'       netcdf file :  VAR-name.nc'
-      PRINT *,'         variables :  either voheatc or vohsalt'
+      PRINT *,'       netcdf file :  VAR-name.nc (or specified with -o option)'
+      PRINT *,'         variables :  either voheatc or vohsalt, unless -tmean or -smean used'
+      PRINT *,'               In this latter case, variables are ',TRIM(cn_votemper),' and '
+      PRINT *,'              ',TRIM(cn_vosaline)
       PRINT *,'      '
       PRINT *,'     SEE ALSO :'
       PRINT *,'        cdfvertmean, cdfheatc, cdfmxlhcsc and  cdfmxlheatc'
@@ -102,8 +117,13 @@ PROGRAM cdfvint
    DO WHILE ( ijarg <= narg ) 
       CALL getarg (ijarg, cldum) ; ijarg = ijarg + 1
       SELECT CASE ( cldum)
-      CASE ( '-GSOP' ) ; lgsop = .TRUE. 
+      CASE ( '-GSOP' ) ; lgsop = .TRUE.
+      CASE ( '-OCCI' ) ; locci = .TRUE.
       CASE ( '-full' ) ; lfull = .TRUE. 
+      CASE ( '-nc4'  ) ; lnc4  = .TRUE. 
+      CASE ( '-tmean') ; ltmean= .TRUE. 
+      CASE ( '-smean') ; lsmean= .TRUE. 
+      CASE ( '-o'    ) ; lfout = .TRUE. ; CALL getarg (ijarg, cf_out) ; ijarg = ijarg + 1
       CASE DEFAULT     
          ij = ij + 1
          SELECT CASE ( ij)
@@ -120,18 +140,41 @@ PROGRAM cdfvint
    lchk = chkfile ( cn_fhgr ) .OR. lchk
    lchk = chkfile ( cn_fzgr ) .OR. lchk
    IF ( lchk ) STOP ! missing files
+  
+   IF ( ltmean .AND. cv_in == cn_vosaline ) THEN
+       PRINT *,' WARNING : flag -tmean is useless with variable', TRIM(cv_in)
+       ltmean = .FALSE.
+   ENDIF
+   IF ( lsmean .AND. cv_in == cn_votemper ) THEN
+       PRINT *,' WARNING : flag -smean is useless with variable', TRIM(cv_in)
+       lsmean = .FALSE.
+   ENDIF
+
 
    ! Set output information according to variable name
    IF ( cv_in == cn_votemper ) THEN
-      cv_out    = 'voheatc'
-      clongname = 'Heat Content per unit area'
-      cunits    = 'J Km^-2'
-      sclf      = pprho0*ppcp/1.e6
+      IF ( ltmean ) THEN
+        cv_out    = cn_votemper
+        clongname = 'Mean temperature '
+        cunits    = 'Deg Celsius'
+        sclf      = 1.
+      ELSE
+        cv_out    = 'voheatc'
+        clongname = 'Heat Content per unit area'
+        cunits    = '10^6 J/m2'
+        sclf      = pprho0*ppcp/1.e6
+      ENDIF
    ELSEIF ( cv_in == cn_vosaline ) THEN
-      cv_out    = 'vohsalt'
-      clongname = 'Vertically Integrated Salinity'
-      cunits    = 'psu*m'
-      sclf      =1.
+      IF ( lsmean ) THEN
+         cv_out    = cn_vosaline
+         clongname = 'Mean salinity'
+         cunits    = 'psu'
+      ELSE
+         cv_out    = 'vohsalt'
+         clongname = 'Vertically Integrated Salinity'
+         cunits    = 'psu.m'
+      ENDIF
+      sclf      = 1.
    ELSE
       PRINT *,'  ERROR: Variable ', TRIM(cv_in), ' not pre-defined ...'
       PRINT *,'     Accepted variables are ', TRIM(cn_votemper),' and ',TRIM(cn_vosaline)
@@ -139,7 +182,7 @@ PROGRAM cdfvint
    ENDIF
 
    ! log information so far
-   cf_out = TRIM(cv_out)//'.nc'
+   IF ( .NOT. lfout ) cf_out = TRIM(cv_out)//'.nc'
    PRINT *,' INPUT VARIABLE  : ' , TRIM(cv_in)
    PRINT *,' OUTPUT VARIABLE : ' , TRIM(cv_out)
    PRINT *,' OUTPUT FILE     : ' , TRIM(cf_out)
@@ -149,8 +192,13 @@ PROGRAM cdfvint
    npk    = getdim (cf_in, cn_z )
    npt    = getdim (cf_in, cn_t )
 
-   IF ( lgsop ) THEN ; PRINT *,' using GSOP depths' ; npko = 7
-                ELSE ; PRINT *,' using model depths'; npko = npk
+   IF ( lgsop ) THEN ; PRINT *,' using GSOP depths' ; npko = 7 ! SL: commented out
+   ENDIF
+
+   IF ( locci ) THEN ; PRINT *,' using OCCIPUT depths' ; npko = 3
+   ENDIF
+   
+   IF ((.not.lgsop).and.(.not.locci)) THEN ; PRINT *,' using model depths'; npko = npk
    ENDIF
 
    PRINT *, ' NPIGLO = ', npiglo
@@ -171,6 +219,10 @@ PROGRAM cdfvint
 
    ! prepare output variable
    ipk(:)                       = npko
+  ! choose chunk size for output ... not easy not used if lnc4=.false. but
+  ! anyway ..
+   stypvar(1)%ichunk=(/npiglo,MAX(1,npjglo/30),1,1 /)
+
    stypvar(1)%cname             = TRIM(cv_out)
    stypvar(1)%cunits            = TRIM(cunits)
    stypvar(1)%rmissing_value    = 0.
@@ -186,15 +238,24 @@ PROGRAM cdfvint
    e31d(:)  = getvare3(cn_fzgr, cn_ve3t,  npk )
 
    IF ( lgsop ) THEN
-      gdepo(:) = (/100.,300.,700.,1500.,3000.,4000.,6000./)
-   ELSE  
+   gdepo(:) = (/100.,300.,500.,700.,800.,2000.,6000./) ! GEOP standard levs
+   ENDIF
+
+   IF ( locci ) THEN 
+   gdepo(:) = (/700.,2000.,6000./) ! SL: occiput levels
+   ENDIF
+
+   IF ((.not.lgsop).and.(.not.locci)) THEN 
       gdepo(1:npk-1) = gdepw(2:npk)
       gdepo(npk)     = 6000.
    ENDIF
 
+
+
    PRINT*,'OUTPUT DEPTHS ARE : ',gdepo
-   ncout = create      (cf_out, 'none', npiglo, npjglo, npko, cdep=cn_vdepthw, ld_xycoo=.FALSE.)
-   ierr  = createvar   (ncout, stypvar, 1, ipk, id_varout )
+   ncout = create      (cf_out, 'none', npiglo, npjglo, npko, cdep=cn_vdepthw, ld_xycoo=.FALSE. &
+                            , ld_nc4=lnc4)
+   ierr  = createvar   (ncout, stypvar, 1, ipk, id_varout , ld_nc4=lnc4)
    ierr  = putheadervar(ncout, cf_in,   npiglo, npjglo, npko, pdep=gdepo,     ld_xycoo=.FALSE.)
 
    tim   = getvar1d    (cf_in, cn_vtimec, npt     )
@@ -208,7 +269,7 @@ PROGRAM cdfvint
       rdep1 = 0.0 ; rdep2 = 0.0
       lout = .TRUE.
       DO jk = 1, npk
-         IF ( lgsop ) lout = .FALSE.
+         IF ( lgsop .OR. locci ) lout = .FALSE.
          rdep1          = rdep2
          dl_vint2(:,:) = dl_vint1 (:,:)
 
@@ -234,7 +295,11 @@ PROGRAM cdfvint
                PRINT *,'Output for level ',iko
                PRINT *,'rdep1, rdep2, depo ',rdep1,rdep2,gdepo(iko) 
             ENDIF
-            ierr = putvar(ncout, id_varout(1) ,REAL(dl_vint2), iko, npiglo, npjglo, ktime=jt)
+            IF ( ltmean .OR. lsmean ) THEN
+               ierr = putvar(ncout, id_varout(1) ,REAL(dl_vint2)/rdep2, iko, npiglo, npjglo, ktime=jt)
+            ELSE
+               ierr = putvar(ncout, id_varout(1) ,REAL(dl_vint2), iko, npiglo, npjglo, ktime=jt)
+            ENDIF
             iko = iko + 1
          ENDIF
       END DO  ! loop to next level
diff --git a/cdfvita-geo.f90 b/src/cdfvita-geo.f90
similarity index 100%
rename from cdfvita-geo.f90
rename to src/cdfvita-geo.f90
diff --git a/cdfvita.f90 b/src/cdfvita.f90
similarity index 63%
rename from cdfvita.f90
rename to src/cdfvita.f90
index 947f405..f38b28b 100644
--- a/cdfvita.f90
+++ b/src/cdfvita.f90
@@ -31,6 +31,9 @@ PROGRAM cdfvita
    INTEGER(KIND=4)                            :: nlev, ik                ! number of selected levels, current lev
    INTEGER(KIND=4)                            :: ncout                   ! ncid of output file
    INTEGER(KIND=4)                            :: ierr                    ! error status for cdfio
+   INTEGER(KIND=4)                            :: ivar                    ! variable index
+   INTEGER(KIND=4)                            :: ivar_vert               ! variable index of vertical velocity
+   INTEGER(KIND=4)                            :: ivar_cub                ! variable index of cube of velocity module
    INTEGER(KIND=4)                            :: nvar                    ! number of variable
    INTEGER(KIND=4), DIMENSION(:), ALLOCATABLE :: nklev                   ! selected levels
    INTEGER(KIND=4), DIMENSION(:), ALLOCATABLE :: ipk, id_varout          ! output stuff
@@ -52,12 +55,15 @@ PROGRAM cdfvita
    LOGICAL                                    :: lvertical = .FALSE.     ! vertical velocity  flag 
    LOGICAL                                    :: lperio    = .FALSE.     ! E_W periodicity flag 
    LOGICAL                                    :: lgeo      = .FALSE.     ! input U V files are geostrophic files
+   LOGICAL                                    :: lcub      = .FALSE.     ! save U*U*U on  A grid
+   LOGICAL                                    :: lnc4      = .FALSE.     ! Use nc4 with chunking and deflation
    !!----------------------------------------------------------------------
    CALL ReadCdfNames()
 
    narg= iargc()
    IF ( narg == 0 ) THEN
-      PRINT *,' usage : cdfvita U-file V_file T-file [-w W-file] [-geo ] [-lev level_list]'
+      PRINT *,' usage : cdfvita U-file V_file T-file [-w W-file] [-geo ] [-cubic] [-nc4] ...'
+      PRINT *,'                 ... [-o OUT-file] [-lev level_list]'
       PRINT *,'      '
       PRINT *,'     PURPOSE :'
       PRINT *,'       Create a file with velocity components, module  and direction'
@@ -76,6 +82,11 @@ PROGRAM cdfvita
       PRINT *,'       [ -geo ]     : indicate that input velocity files are produced '
       PRINT *,'                      by cdfgeo-uv, hence ugeo on V-point, vgeo on U-points'
       PRINT *,'                      ( U-file and V_file are the same !)'
+      PRINT *,'       [ -cubic ]   : Save the cube of the veocity module '
+      PRINT *,'       [ -nc4 ]     : Use netcdf4 output with chunking and deflation level 1'
+      PRINT *,'                 This option is effective only if cdftools are compiled with'
+      PRINT *,'                 a netcdf library supporting chunking and deflation.'
+      PRINT *,'       [ -o OUT-file ] : Specify name of output file instead of ',TRIM(cf_out)
       PRINT *,'       [ -lev level_list] : specify a list of level to be used '
       PRINT *,'                   (default option is to use all input levels).'
       PRINT *,'                   This option MUST be the last on the command line !!'
@@ -84,8 +95,8 @@ PROGRAM cdfvita
       PRINT *,'        none'
       PRINT *,'      '
       PRINT *,'     OUTPUT : '
-      PRINT *,'       netcdf file : ', TRIM(cf_out) 
-      PRINT *,'         variables : sovitua, sovitva, sovitmod, sovitdir, [sovitwa]'
+      PRINT *,'       netcdf file : ', TRIM(cf_out) ,' unless -o option is used'
+      PRINT *,'         variables : sovitua, sovitva, sovitmod, sovitdir, [sovitmod3], [sovitwa]'
       STOP
    ENDIF
 
@@ -106,6 +117,12 @@ PROGRAM cdfvita
          lvertical=.TRUE.
       CASE ( '-geo' )
          lgeo = .TRUE.
+      CASE ( '-cubic' )
+         lcub = .TRUE.
+      CASE ( '-nc4' )
+         lnc4 = .TRUE.
+      CASE ( '-o' )
+        CALL getarg( ijarg, cf_out ) ; ijarg=ijarg+1
       CASE DEFAULT
          cf_ufil=cldum
          CALL getarg( ijarg, cf_vfil ) ; ijarg=ijarg+1
@@ -115,7 +132,9 @@ PROGRAM cdfvita
 
    ! adjust number of variable according to -w option
    nvar=4
-   IF ( lvertical )  nvar = 5
+   IF ( lvertical )  nvar = nvar + 1
+   IF ( lcub      )  nvar = nvar + 1
+
 
    ALLOCATE ( ipk(nvar), id_varout(nvar), stypvar(nvar) )
 
@@ -143,69 +162,98 @@ PROGRAM cdfvita
    ENDIF
 
    ALLOCATE ( gdept(nlev) )
+   ivar=0
 
    ! Zonal Velocity T point
-   ipk(1)                       = nlev
-   stypvar(1)%cname             = 'sovitua'
-   stypvar(1)%cunits            = 'm/s'
-   stypvar(1)%rmissing_value    = 0.
-   stypvar(1)%valid_min         = 0.
-   stypvar(1)%valid_max         = 10000.
-   stypvar(1)%clong_name        = 'Zonal Velocity T point'
-   stypvar(1)%cshort_name       = 'sovitua'
-   stypvar(1)%conline_operation = 'N/A'
-   stypvar(1)%caxis             = 'TZYX'
+   ivar                            = ivar+1
+   ipk(ivar)                       = nlev
+   stypvar(ivar)%ichunk            = (/npiglo,MAX(1,npjglo/30),1,1 /)
+   stypvar(ivar)%cname             = 'sovitua'
+   stypvar(ivar)%cunits            = 'm/s'
+   stypvar(ivar)%rmissing_value    = 0.
+   stypvar(ivar)%valid_min         = 0.
+   stypvar(ivar)%valid_max         = 10000.
+   stypvar(ivar)%clong_name        = 'Zonal Velocity T point'
+   stypvar(ivar)%cshort_name       = 'sovitua'
+   stypvar(ivar)%conline_operation = 'N/A'
+   stypvar(ivar)%caxis             = 'TZYX'
 
    ! Meridional Velocity T point
-   ipk(2)                       = nlev
-   stypvar(2)%cname             = 'sovitva'
-   stypvar(2)%cunits            = 'm/s'
-   stypvar(2)%rmissing_value    = 0.
-   stypvar(2)%valid_min         = 0.
-   stypvar(2)%valid_max         = 10000.
-   stypvar(2)%clong_name        = 'Meridional Velocity T point'
-   stypvar(2)%cshort_name       = 'sovitva'
-   stypvar(2)%conline_operation = 'N/A'
-   stypvar(2)%caxis             = 'TZYX'
-
-   ! Velocity module T point
-   ipk(3)                       = nlev
-   stypvar(3)%cname             = 'sovitmod'
-   stypvar(3)%cunits            = 'm/s'
-   stypvar(3)%rmissing_value    = 0.
-   stypvar(3)%valid_min         = 0.
-   stypvar(3)%valid_max         = 10000.
-   stypvar(3)%clong_name        = 'Velocity module T point'
-   stypvar(3)%cshort_name       = 'sovitmod'
-   stypvar(3)%conline_operation = 'N/A'
-   stypvar(3)%caxis             = 'TZYX'
+   ivar                            = ivar+1
+   ipk(ivar)                       = nlev
+   stypvar(ivar)%ichunk            = (/npiglo,MAX(1,npjglo/30),1,1 /)
+   stypvar(ivar)%cname             = 'sovitva'
+   stypvar(ivar)%cunits            = 'm/s'
+   stypvar(ivar)%rmissing_value    = 0.
+   stypvar(ivar)%valid_min         = 0.
+   stypvar(ivar)%valid_max         = 10000.
+   stypvar(ivar)%clong_name        = 'Meridional Velocity T point'
+   stypvar(ivar)%cshort_name       = 'sovitva'
+   stypvar(ivar)%conline_operation = 'N/A'
+   stypvar(ivar)%caxis             = 'TZYX'
 
    ! Velocity module T point
-   ipk(4)                       = nlev
-   stypvar(4)%cname             = 'sovitdir'
-   stypvar(4)%cunits            = 'deg N'
-   stypvar(4)%rmissing_value    = 0.
-   stypvar(4)%valid_min         = 0.
-   stypvar(4)%valid_max         = 360.
-   stypvar(4)%clong_name        = 'Velocity direction T point'
-   stypvar(4)%cshort_name       = 'sovitdir'
-   stypvar(4)%conline_operation = 'N/A'
-   stypvar(4)%caxis             = 'TZYX'
+   ivar                            = ivar+1
+   ipk(ivar)                       = nlev
+   stypvar(ivar)%ichunk            = (/npiglo,MAX(1,npjglo/30),1,1 /)
+   stypvar(ivar)%cname             = 'sovitmod'
+   stypvar(ivar)%cunits            = 'm/s'
+   stypvar(ivar)%rmissing_value    = 0.
+   stypvar(ivar)%valid_min         = 0.
+   stypvar(ivar)%valid_max         = 10000.
+   stypvar(ivar)%clong_name        = 'Velocity module T point'
+   stypvar(ivar)%cshort_name       = 'sovitmod'
+   stypvar(ivar)%conline_operation = 'N/A'
+   stypvar(ivar)%caxis             = 'TZYX'
+
+   ! Velocity direction  T point
+   ivar                            = ivar+1
+   ipk(ivar)                       = nlev
+   stypvar(ivar)%ichunk            = (/npiglo,MAX(1,npjglo/30),1,1 /)
+   stypvar(ivar)%cname             = 'sovitdir'
+   stypvar(ivar)%cunits            = 'deg N'
+   stypvar(ivar)%rmissing_value    = 0.
+   stypvar(ivar)%valid_min         = 0.
+   stypvar(ivar)%valid_max         = 360.
+   stypvar(ivar)%clong_name        = 'Velocity direction T point'
+   stypvar(ivar)%cshort_name       = 'sovitdir'
+   stypvar(ivar)%conline_operation = 'N/A'
+   stypvar(ivar)%caxis             = 'TZYX'
 
 
 
    IF ( lvertical ) THEN
       ! Vertical Velocity at T point
-      ipk(nvar)                       = nlev
-      stypvar(nvar)%cname             = 'sovitwa'
-      stypvar(nvar)%cunits            = 'mm/s'
-      stypvar(nvar)%rmissing_value    = 0.
-      stypvar(nvar)%valid_min         = 0.
-      stypvar(nvar)%valid_max         = 10000.
-      stypvar(nvar)%clong_name        = 'Vertical Velocity at T point'
-      stypvar(nvar)%cshort_name       = 'sovitwa'
-      stypvar(nvar)%conline_operation = 'N/A'
-      stypvar(nvar)%caxis             = 'TZYX'
+      ivar                            = ivar+1
+      ivar_vert                       = ivar
+      ipk(ivar)                       = nlev
+      stypvar(ivar)%ichunk            = (/npiglo,MAX(1,npjglo/30),1,1 /)
+      stypvar(ivar)%cname             = 'sovitwa'
+      stypvar(ivar)%cunits            = 'mm/s'
+      stypvar(ivar)%rmissing_value    = 0.
+      stypvar(ivar)%valid_min         = 0.
+      stypvar(ivar)%valid_max         = 10000.
+      stypvar(ivar)%clong_name        = 'Vertical Velocity at T point'
+      stypvar(ivar)%cshort_name       = 'sovitwa'
+      stypvar(ivar)%conline_operation = 'N/A'
+      stypvar(ivar)%caxis             = 'TZYX'
+   ENDIF
+
+   IF ( lcub ) THEN
+      ! Cube of velocity module
+      ivar                            = ivar+1
+      ivar_cub                        = ivar
+      ipk(ivar)                       = nlev
+      stypvar(ivar)%ichunk            = (/npiglo,MAX(1,npjglo/30),1,1 /)
+      stypvar(ivar)%cname             = 'sovitmod3'
+      stypvar(ivar)%cunits            = 'm3/s3'
+      stypvar(ivar)%rmissing_value    = 0.
+      stypvar(ivar)%valid_min         = 0.
+      stypvar(ivar)%valid_max         = 10000.
+      stypvar(ivar)%clong_name        = 'cube of velocity module'
+      stypvar(ivar)%cshort_name       = 'sovitmod3'
+      stypvar(ivar)%conline_operation = 'N/A'
+      stypvar(ivar)%caxis             = 'TZYX'
    ENDIF
 
    PRINT *, 'npiglo =', npiglo
@@ -232,8 +280,8 @@ PROGRAM cdfvita
       PRINT *,' E-W periodicity detected.'
    ENDIF
 
-   ncout = create      (cf_out,   cf_tfil,  npiglo, npjglo, nlev                 )
-   ierr  = createvar   (ncout ,   stypvar,  nvar,   ipk,    id_varout            )
+   ncout = create      (cf_out,   cf_tfil,  npiglo, npjglo, nlev     , ld_nc4=lnc4 )
+   ierr  = createvar   (ncout ,   stypvar,  nvar,   ipk,    id_varout, ld_nc4=lnc4 )
    ierr  = putheadervar(ncout,    cf_tfil,  npiglo, npjglo, nlev,     pdep=gdept )
 
    DO jt = 1, npt
@@ -270,11 +318,14 @@ PROGRAM cdfvita
             vmod(1,:) = vmod(npiglo-1,:)
             vdir(1,:) = vdir(npiglo-1,:)
          ENDIF
-
-         ierr=putvar(ncout, id_varout(1), ua,   jlev ,npiglo, npjglo, ktime=jt )
-         ierr=putvar(ncout, id_varout(2), va,   jlev ,npiglo, npjglo, ktime=jt )
-         ierr=putvar(ncout, id_varout(3), vmod, jlev ,npiglo, npjglo, ktime=jt )
-         ierr=putvar(ncout, id_varout(4), vdir, jlev ,npiglo, npjglo, ktime=jt )
+         ivar = 1
+         ierr=putvar(ncout, id_varout(ivar), ua,   jlev ,npiglo, npjglo, ktime=jt ) ; ivar = ivar +1
+         ierr=putvar(ncout, id_varout(ivar), va,   jlev ,npiglo, npjglo, ktime=jt ) ; ivar = ivar +1
+         ierr=putvar(ncout, id_varout(ivar), vmod, jlev ,npiglo, npjglo, ktime=jt ) ; ivar = ivar +1
+         ierr=putvar(ncout, id_varout(ivar), vdir, jlev ,npiglo, npjglo, ktime=jt ) 
+         IF ( lcub ) THEN
+           ierr=putvar(ncout, id_varout(ivar_cub), vmod*vmod*vmod, jlev ,npiglo, npjglo, ktime=jt ) 
+         ENDIF
       END DO
    END DO
 
@@ -285,7 +336,7 @@ PROGRAM cdfvita
             uc(:,:) = getvar(cf_wfil, cn_vovecrtz, nklev(jlev),   npiglo, npjglo, ktime=jt )
             vc(:,:) = getvar(cf_wfil, cn_vovecrtz, nklev(jlev)+1, npiglo, npjglo, ktime=jt )
             ua(:,:) = 0.5*(uc(:,:) + vc(:,:))*1000.  ! mm/sec
-            ierr    = putvar(ncout, id_varout(4), ua, jlev,      npiglo, npjglo, ktime=jt )
+            ierr    = putvar(ncout, id_varout(ivar_vert), ua, jlev,      npiglo, npjglo, ktime=jt )
             uc(:,:) = vc(:,:)
          END DO
          IF ( nlev == npk ) THEN
@@ -295,7 +346,7 @@ PROGRAM cdfvita
             vc(:,:) = getvar(cf_wfil, cn_vovecrtz, nklev(nlev)+1, npiglo, npjglo, ktime=jt )
             ua(:,:) = 0.5*(uc(:,:) + vc(:,:))*1000.  ! mm/sec
          ENDIF
-         ierr = putvar(ncout, id_varout(4), ua, nlev ,npiglo, npjglo, ktime=jt )
+         ierr = putvar(ncout, id_varout(ivar_vert), ua, nlev ,npiglo, npjglo, ktime=jt )
       ENDDO
    ENDIF
 
diff --git a/src/cdfvsig.f90 b/src/cdfvsig.f90
new file mode 100644
index 0000000..f9c6ad8
--- /dev/null
+++ b/src/cdfvsig.f90
@@ -0,0 +1,579 @@
+PROGRAM cdfvsig
+  !!======================================================================
+  !!                     ***  PROGRAM  cdfvsig  ***
+  !!=====================================================================
+  !!  ** Purpose : Compute the average values for the products 
+  !!               U.sig, V.sig, W.sig where sig is the potential density.
+  !!
+  !!  ** Method  : pass the CONFIG name and a series of tags as arguments.
+  !!               Tracers are interpolated on velocity points. The product
+  !!               is evaluated at velocity points.
+  !!
+  !! History : 2.1  : 11/2004  : J.M. Molines : Original code
+  !!           2.1  : 02/2010  : J.M. Molines : handle multiframes input files.
+  !!           3.0  : 04/2011  : J.M. Molines : Doctor norm + Lic.
+  !!----------------------------------------------------------------------
+  USE cdfio
+  USE eos
+  USE modcdfnames
+  USE modutils
+  !!----------------------------------------------------------------------
+  !! CDFTOOLS_3.0 , MEOM 2011
+  !! $Id$
+  !! Copyright (c) 2011, J.-M. Molines
+  !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+  !!----------------------------------------------------------------------
+  IMPLICIT NONE
+
+  INTEGER(KIND=4)                           :: ji, jj, jk, jt, jtt  ! dummy loop index
+  INTEGER(KIND=4)                           :: jsig                 ! dummy loop index
+  INTEGER(KIND=4)                           :: ierr                 ! working integer
+  INTEGER(KIND=4)                           :: narg, iargc          ! command line
+  INTEGER(KIND=4)                           :: ijarg, iiarg         ! argument counter
+  INTEGER(KIND=4)                           :: ndep                 ! number of reference depth to deal with
+  INTEGER(KIND=4)                           :: npiglo,npjglo        ! size of the domain
+  INTEGER(KIND=4)                           :: npk, npt             ! size of the domain
+  INTEGER(KIND=4)                           :: ntframe              ! Cumul of time frame
+  INTEGER(KIND=4)                           :: nopt                 ! number of options
+  INTEGER(KIND=4)                           :: ncoutu               ! ncid of output file
+  INTEGER(KIND=4)                           :: ncoutv               ! ncid of output file
+  INTEGER(KIND=4)                           :: ncoutw               ! ncid of output file
+  INTEGER(KIND=4)                           :: nfieldu, nfieldv, nfieldw  ! ncid of output file
+  INTEGER(KIND=4)                           :: ivaru, ivarv, ivarw  ! variable counter
+  INTEGER(KIND=4), DIMENSION(:), ALLOCATABLE :: ipku, id_varoutu     ! level and varid's of output vars
+  INTEGER(KIND=4), DIMENSION(:), ALLOCATABLE :: ipkv, id_varoutv     ! level and varid's of output vars
+  INTEGER(KIND=4), DIMENSION(:), ALLOCATABLE :: ipkw, id_varoutw     ! level and varid's of output vars
+
+  REAL(KIND=4)                              :: zdepref              ! reference level for potential density
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: ztemp,  zsal         ! Array to read a layer of data
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: zu, zv, zw           ! Velocity component
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: ztempu, zsalu        ! Array to read a layer of data
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: ztempv, zsalv        ! Array to read a layer of data
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: ztempw, zsalw        ! Array to read a layer of data
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: umask,  vmask, wmask ! masks
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: refdep               ! Reference depth table
+  REAL(KIND=4), DIMENSION(:),   ALLOCATABLE :: tim                  ! time counter of individual files
+  REAL(KIND=4), DIMENSION(1)                :: timean               ! mean time
+
+  REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dcumulus             ! Arrays for cumulated values
+  REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dcumulvs             ! Arrays for cumulated values
+
+  REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dcumulws             ! Arrays for cumulated values
+  REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dcumulsu             ! Arrays for cumulated values
+  REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dcumulsv             ! Arrays for cumulated values
+  REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dcumulsw             ! Arrays for cumulated values
+  REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dsigu                ! Array for sigmai at u point
+  REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dsigv                ! Array for sigmai at v point
+  REAL(KIND=8), DIMENSION(:,:,:), ALLOCATABLE :: dsigw                ! Array for sigmai at w point
+  REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dcumulu, dcumulu2    ! Arrays for cumulated values
+  REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dcumulv, dcumulv2    ! Arrays for cumulated values
+  REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dcumulw, dcumulw2    ! Arrays for cumulated values
+  REAL(KIND=8)                              :: dtotal_time          ! cumulated time
+
+  CHARACTER(LEN=256)                        :: cf_tfil              ! TS file name
+  CHARACTER(LEN=256)                        :: cf_ufil              ! zonal velocity file
+  CHARACTER(LEN=256)                        :: cf_vfil              ! meridional velocity file
+  CHARACTER(LEN=256)                        :: cf_wfil              ! vertical velocity file
+  CHARACTER(LEN=256)                        :: cf_outu='usig.nc'    ! output file
+  CHARACTER(LEN=256)                        :: cf_outv='vsig.nc'    ! output file
+  CHARACTER(LEN=256)                        :: cf_outw='wsig.nc'    ! output file
+  CHARACTER(LEN=256)                        :: config               ! configuration name
+  CHARACTER(LEN=256)                        :: ctag                 ! current tag to work with               
+  CHARACTER(LEN=256)                        :: cldum                ! dummy character var for browsing
+
+  TYPE (variable), DIMENSION(:), ALLOCATABLE :: stypvaru             ! structure for attributes
+  TYPE (variable), DIMENSION(:), ALLOCATABLE :: stypvarv             ! structure for attributes
+  TYPE (variable), DIMENSION(:), ALLOCATABLE :: stypvarw             ! structure for attributes
+
+  LOGICAL                                   :: lcaltmean            ! flag for mean time computation
+  LOGICAL                                   :: lwo=.true.           ! flag for -no-w option
+  LOGICAL                                   :: lsigo=.true.         ! flag for -no-sig option
+  LOGICAL                                   :: luvo=.true.          ! flag for -no-uv option
+  LOGICAL                                   :: lTpt=.false.         ! flag for -no-uv option
+  LOGICAL                                   :: lpref=.false.        ! flag for -pref option
+  LOGICAL                                   :: lperio=.false.       ! checking E-W periodicity
+
+  !!----------------------------------------------------------------------
+  CALL ReadCdfNames()
+
+  !!  Read command line
+  narg= iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' usage : cdfvsig CONFIG  [-no-w] [-no-sig]  [-no-uv] [-T ] [-pref pref1,pref2,...]'
+     PRINT *,'        ... ''list_of_tags'' '
+     PRINT *,'     PURPOSE :'
+     PRINT *,'       Compute the time average values for second order products ' 
+     PRINT *,'       U.sig,  V.sig and W.sig.  Also save mean sigma-0 interpolated at'
+     PRINT *,'       velocity points, as well as mean velocity component, for further use.'
+     PRINT *,'      '
+     PRINT *,'     ARGUMENTS :'
+     PRINT *,'       CONFIG is the config name of a given experiment (eg ORCA025-G70)'
+     PRINT *,'            The program will look for gridT, gridU, gridV  and gridW files for' 
+     PRINT *,'            this config ( grid_T, grid_U, grid_V and grid_W are also accepted).'
+     PRINT *,'       list_of_tags : a list of time tags that will be used for time'
+     PRINT *,'            averaging. e.g. y2000m01d05 y2000m01d10.'
+     PRINT *,'            ! IMPORTANT : list_of_tag are at the end of the command line ! '
+     PRINT *,'      '
+     PRINT *,'     OPTIONS ( to be used before the list_of tags ):'
+     PRINT *,'        -T : compute u and v at T points, so that usig, vsig will be at T point'
+     PRINT *,'        -no-w : no computation of vertical products'
+     PRINT *,'        -no-sig : no output of density on U V points'
+     PRINT *,'        -no-uv : no output of mean velocity components'
+     PRINT *,'        -pref pref1,pref2,..: give comma separated list of reference depths for'
+     PRINT *,'             density computation. eg : -pref 0,2000,3000  If not specified '
+     PRINT *,'             assumes pref=0.'
+     PRINT *,'      '
+     PRINT *,'     REQUIRED FILES :'
+     PRINT *,'        ',TRIM(cn_fmsk)
+     PRINT *,'      '
+     PRINT *,'     OUTPUT : '
+     PRINT *,'       netcdf file : ', TRIM(cf_outu),', ',TRIM(cf_outv),' and ', TRIM(cf_outw)
+     PRINT *,'       variables : vousig, vovsig, vowsig : mean product v x sigma-0 '
+     PRINT *,'                                            at velocity point.'
+     PRINT *,'                   vosigu, vosigv, vosigw : mean sigma-0 at velocity point.'
+     PRINT *,'                   ',TRIM(cn_vozocrtx),', ',TRIM(cn_vomecrty),', ',TRIM(cn_vovecrtz),' : mean velocity components.'
+     STOP
+  ENDIF
+
+  !! Initialisation from 1st file (all file are assume to have the same geometry)
+  ijarg = 1 ; iiarg=0 ; nopt=0
+  DO WHILE ( ijarg <= narg )
+     CALL getarg(ijarg, cldum) ; ijarg=ijarg+1
+     SELECT CASE ( cldum )
+     CASE ( '-no-w'   ) ; lwo=.false.   ; nopt=nopt+1
+     CASE ( '-no-sig' ) ; lsigo=.false. ; nopt=nopt+1
+     CASE ( '-no-uv'  ) ; luvo=.false.  ; nopt=nopt+1
+     CASE ( '-T'      ) ; lTpt=.true.   ; nopt=nopt+1
+     CASE ( '-pref'   ) ; lpref=.true.  ; CALL getarg(ijarg, cldum) ; ijarg=ijarg+1 
+        CALL ParseRefDep(cldum)
+        nopt=nopt+2 ! this option count for 2 args
+     CASE DEFAULT
+        iiarg=iiarg+1
+        SELECT CASE (iiarg)
+        CASE ( 1 )  ; config=cldum ;  nopt=nopt+1
+        CASE ( 2 )  ; ctag=cldum
+        END SELECT
+     END SELECT
+  END DO
+
+  ! initialize refdep if not done on command line
+  IF ( .NOT. lpref ) THEN
+     ndep = 1
+     ALLOCATE(refdep(ndep) )
+     refdep(1) =0.0
+  ENDIF
+
+  ! |  always            |   if lsigo        |   if luvo    |
+  ! | ndep [ u x sigma ] +   ndep [ sigma ]  +  2 [ u, u2 ] |
+  nfieldu = ndep + ndep * COUNT ( (/lsigo /)  ) + 2 * COUNT ( (/luvo/) )
+  nfieldv = nfieldu
+  nfieldw = 2 * COUNT ( (/lwo /)) * nfieldu
+
+  cf_tfil = SetFileName ( config, ctag, 'T')
+  cf_ufil = SetFileName ( config, ctag, 'U')
+  cf_vfil = SetFileName ( config, ctag, 'V')
+  IF ( lwo ) cf_wfil = SetFileName ( config, ctag, 'W')
+
+  npiglo = getdim (cf_tfil,cn_x)
+  npjglo = getdim (cf_tfil,cn_y)
+  npk    = getdim (cf_tfil,cn_z)
+
+  PRINT *, 'npiglo =', npiglo
+  PRINT *, 'npjglo =', npjglo
+  PRINT *, 'npk    =', npk
+
+  ALLOCATE( dcumulus(npiglo,npjglo,ndep), dcumulvs(npiglo,npjglo,ndep) )
+  ALLOCATE( ztemp(npiglo,npjglo),    zsal(npiglo,npjglo)               )
+  ALLOCATE( ztempu(npiglo,npjglo),  zsalu(npiglo,npjglo)               )
+  ALLOCATE( ztempv(npiglo,npjglo),  zsalv(npiglo,npjglo)               )
+  ALLOCATE( zu(npiglo,npjglo),       zv(npiglo,npjglo)                 )
+  ALLOCATE( dsigu(npiglo,npjglo,ndep),    dsigv(npiglo,npjglo,ndep)    )
+  ALLOCATE( umask(npiglo,npjglo),    vmask(npiglo,npjglo),    wmask(npiglo,npjglo)    )
+
+  IF ( lwo   )           ALLOCATE( dcumulws(npiglo,npjglo,ndep) )
+  IF ( lsigo )           ALLOCATE( dcumulsu(npiglo,npjglo,ndep), dcumulsv(npiglo,npjglo,ndep) )
+  IF ( lwo .AND. lsigo ) ALLOCATE( dcumulsw(npiglo,npjglo,ndep) )
+  IF ( luvo  )           ALLOCATE( dcumulu(npiglo,npjglo),  dcumulv(npiglo,npjglo)  )
+  IF ( luvo  )           ALLOCATE( dcumulu2(npiglo,npjglo), dcumulv2(npiglo,npjglo) )
+  IF ( lwo .AND. luvo  ) ALLOCATE( dcumulw(npiglo,npjglo), dcumulw2(npiglo,npjglo)  )
+
+  IF ( lwo  )  ALLOCATE( zw(npiglo,npjglo)                             )
+  IF ( lwo  )  ALLOCATE( ztempw(npiglo,npjglo),  zsalw(npiglo,npjglo)  )
+  IF ( lwo  )  ALLOCATE( dsigw(npiglo,npjglo,ndep)                     )
+
+  ! check periodicity (use ztemp as dummy array )
+  ztemp(:,:) = getvar(cf_tfil, cn_vlon2d, 1, npiglo, npjglo )
+  IF ( ztemp(1,1) == ztemp(npiglo-1,1) )  THEN
+     lperio = .TRUE.
+     PRINT *,' E-W periodicity detected '
+  ENDIF
+
+
+  CALL CreateOutputFile
+
+  lcaltmean=.TRUE.
+  DO jk = 1, npk
+     PRINT *,'level ',jk
+     dcumulus(:,:,:) = 0.d0 ;  dcumulvs(:,:,:) = 0.d0 
+     IF ( lwo   ) dcumulws(:,:,:) = 0.d0
+     IF ( lsigo ) THEN  ; dcumulsu(:,:,:) = 0.d0 ;  dcumulsv(:,:,:) = 0.d0  ;  ENDIF
+     IF ( lsigo .AND. lwo ) dcumulsw(:,:,:) = 0.d0
+     IF ( luvo  ) THEN   ; dcumulu(:,:)    = 0.d0  ;  dcumulv(:,:)   = 0.d0 ;  ENDIF
+     IF ( luvo  ) THEN   ; dcumulu2(:,:)   = 0.d0  ;  dcumulv2(:,:)  = 0.d0 ;  ENDIF
+     IF (luvo .AND. lwo ) THEN ; dcumulw(:,:) = 0.d0 ; dcumulw2(:,:) = 0.d0 ;  ENDIF
+     dtotal_time   = 0.d0 ;  ntframe     = 0
+
+     umask(:,:) = getvar(cn_fmsk, 'umask' , jk, npiglo, npjglo )
+     vmask(:,:) = getvar(cn_fmsk, 'vmask' , jk, npiglo, npjglo )
+     IF ( lwo .OR. lTpt ) wmask(:,:) = getvar(cn_fmsk, 'tmask' , jk, npiglo, npjglo )
+
+     DO jt = nopt+1, narg            ! loop on tags
+        CALL getarg (jt, ctag)
+        cf_tfil = SetFileName ( config, ctag, 'T' )
+        cf_ufil = SetFileName ( config, ctag, 'U' )
+        cf_vfil = SetFileName ( config, ctag, 'V' )
+        IF ( lwo ) cf_wfil = SetFileName ( config, ctag, 'W' )
+
+        npt = getdim (cf_tfil, cn_t)
+        IF ( lcaltmean ) THEN
+           ALLOCATE ( tim(npt) )
+           tim = getvar1d(cf_tfil, cn_vtimec, npt)
+           dtotal_time = dtotal_time + SUM(tim(1:npt) )
+           DEALLOCATE( tim )
+        END IF
+
+        DO jtt = 1, npt  ! loop on time frame in a single file
+           ntframe    = ntframe+1
+           zu(:,:)    = getvar(cf_ufil, cn_vozocrtx, jk, npiglo, npjglo, ktime=jtt )
+           zv(:,:)    = getvar(cf_vfil, cn_vomecrty, jk, npiglo, npjglo, ktime=jtt )
+           ztemp(:,:) = getvar(cf_tfil, cn_votemper, jk, npiglo, npjglo, ktime=jtt )
+           zsal(:,:)  = getvar(cf_tfil, cn_vosaline, jk, npiglo, npjglo, ktime=jtt )
+           IF ( lwo ) zw(:,:)    = getvar(cf_wfil, cn_vovecrtz, jk, npiglo, npjglo, ktime=jtt )
+
+           dsigu(:,:,:) = 0.d0  ; dsigv(:,:,:) = 0.d0
+           IF ( lTpt )  THEN
+              ! u,v at T point
+              DO ji=npiglo,2,-1
+                 zu(ji,:) = 0.5 * ( zu(ji-1,:) + zu(ji,:) )
+              END DO
+              DO jj=npjglo,2,-1
+                 zv(:,jj) = 0.5 * ( zv(:,jj-1) + zv(:,jj) )
+              END DO
+              IF ( lperio ) THEN
+                 zu(1,:) = zu(npiglo-1,:)
+              ENDIF
+              IF ( luvo ) THEN
+                 dcumulu(:,:)   = dcumulu(:,:)  + zu(:,:)    * 1.d0
+                 dcumulv(:,:)   = dcumulv(:,:)  + zv(:,:)    * 1.d0
+                 dcumulu2(:,:)  = dcumulu2(:,:)  + zu(:,:)*zu(:,:) * 1.d0
+                 dcumulv2(:,:)  = dcumulv2(:,:)  + zv(:,:)*zv(:,:) * 1.d0
+              ENDIF
+              DO jsig=1,ndep
+                 zdepref=refdep(jsig)
+                 ! rem : use dsigu for sig at T point, for the sake of simplicity ...
+                 dsigu(:,:,jsig) = sigmai(ztemp, zsal, zdepref, npiglo, npjglo) * wmask(:,:)
+
+                 dcumulus(:,:,jsig) = dcumulus(:,:,jsig) + dsigu(:,:,jsig) * zu(:,:) * 1.d0
+                 dcumulvs(:,:,jsig) = dcumulvs(:,:,jsig) + dsigu(:,:,jsig) * zv(:,:) * 1.d0
+                 IF ( lsigo ) THEN
+                    dcumulsu(:,:,jsig) = dcumulsu(:,:,jsig) + dsigu(:,:,jsig) * 1.d0
+                 ENDIF
+              ENDDO
+           ELSE
+              ! temperature at u point, v points
+              DO ji=1, npiglo-1
+                 DO jj = 1, npjglo -1
+                    ztempu(ji,jj) = 0.5 * ( ztemp(ji,jj) + ztemp(ji+1,jj) )  ! temper at Upoint
+                    ztempv(ji,jj) = 0.5 * ( ztemp(ji,jj) + ztemp(ji,jj+1) )  ! temper at Vpoint
+                    zsalu(ji,jj)  = 0.5 * ( zsal(ji,jj)  +  zsal(ji+1,jj) )  ! sal at U point
+                    zsalv(ji,jj)  = 0.5 * ( zsal(ji,jj)  +  zsal(ji,jj+1) )  ! sal at v point
+                 END DO
+              END DO
+
+              IF ( luvo ) THEN
+                 dcumulu(:,:)   = dcumulu(:,:)  + zu(:,:)    * 1.d0
+                 dcumulv(:,:)   = dcumulv(:,:)  + zv(:,:)    * 1.d0
+                 dcumulu2(:,:)  = dcumulu2(:,:)  + zu(:,:)*zu(:,:) * 1.d0
+                 dcumulv2(:,:)  = dcumulv2(:,:)  + zv(:,:)*zv(:,:) * 1.d0
+              ENDIF
+              DO jsig=1,ndep
+                 zdepref=refdep(jsig)
+                 dsigu(:,:,jsig) = sigmai(ztempu, zsalu, zdepref, npiglo, npjglo) * umask(:,:)
+                 dsigv(:,:,jsig) = sigmai(ztempv, zsalv, zdepref, npiglo, npjglo) * vmask(:,:)
+
+                 dcumulus(:,:,jsig) = dcumulus(:,:,jsig) + dsigu(:,:,jsig) * zu(:,:) * 1.d0
+                 dcumulvs(:,:,jsig) = dcumulvs(:,:,jsig) + dsigv(:,:,jsig) * zv(:,:) * 1.d0
+                 IF ( lsigo ) THEN
+                    dcumulsu(:,:,jsig) = dcumulsu(:,:,jsig) + dsigu(:,:,jsig) * 1.d0
+                    dcumulsv(:,:,jsig) = dcumulsv(:,:,jsig) + dsigv(:,:,jsig) * 1.d0
+                 ENDIF
+
+                 IF ( lwo ) THEN
+                    IF ( jk > 1 ) THEN ! now wsig
+                       ztempw(:,:)   = 0.5 * ( ztemp(:,:) + getvar(cf_tfil, cn_votemper, jk-1, npiglo, npjglo, ktime=jtt ))
+                       zsalw(:,:)    = 0.5 * ( zsal(:,:)  + getvar(cf_tfil, cn_vosaline, jk-1, npiglo, npjglo, ktime=jtt ))
+                       dsigw(:,:,jsig)    = sigmai(ztempw, zsalw, zdepref, npiglo, npjglo) * wmask(:,:)
+                       dcumulws(:,:,jsig) = dcumulws(:,:,jsig) + dsigw(:,:,jsig) * zw(:,:) * 1.d0
+                       IF ( lsigo ) dcumulsw(:,:,jsig) = dcumulsw(:,:,jsig) + dsigw(:,:,jsig) * 1.d0
+                       IF ( luvo  ) dcumulw(:,:)   = dcumulw(:,:)   + zw(:,:)         * 1.d0
+                       IF ( luvo  ) dcumulw2(:,:)  = dcumulw2(:,:)  + zw(:,:)*zw(:,:) * 1.d0
+                    ENDIF
+                 ENDIF
+              ENDDO
+           ENDIF  ! Tpoint
+
+        END DO  !jtt
+     END DO  ! jt
+     ! finish with level jk ; compute mean (assume spval is 0 )
+     ivaru=0 ; ivarv=0 ; ivarw=0
+     !    U
+     DO jsig=1,ndep
+        ivaru=ivaru + 1
+        ierr = putvar(ncoutu, id_varoutu(ivaru), SNGL(dcumulus(:,:,jsig)/ntframe), jk, npiglo, npjglo, kwght=ntframe )
+        IF ( lsigo) THEN 
+           ivaru=ivaru + 1
+           ierr = putvar(ncoutu, id_varoutu(ivaru), SNGL(dcumulsu(:,:,jsig)/ntframe), jk, npiglo, npjglo, kwght=ntframe )
+        ENDIF
+     END DO
+
+     IF ( luvo ) THEN 
+        ivaru=ivaru + 1
+        ierr = putvar(ncoutu, id_varoutu(ivaru), SNGL(dcumulu(:,:)      /ntframe), jk, npiglo, npjglo, kwght=ntframe )
+        ivaru=ivaru + 1
+        ierr = putvar(ncoutu, id_varoutu(ivaru), SNGL(dcumulu2(:,:)     /ntframe), jk, npiglo, npjglo, kwght=ntframe )
+     ENDIF
+
+     !    V
+     DO jsig=1,ndep
+        ivarv=ivarv + 1
+        ierr = putvar(ncoutv, id_varoutv(ivarv), SNGL(dcumulvs(:,:,jsig)/ntframe), jk, npiglo, npjglo, kwght=ntframe )
+        IF ( lsigo) THEN 
+           ivarv=ivarv + 1
+           ierr = putvar(ncoutv, id_varoutv(ivarv), SNGL(dcumulsv(:,:,jsig)/ntframe), jk, npiglo, npjglo, kwght=ntframe )
+        ENDIF
+     ENDDO
+     IF ( luvo ) THEN 
+        ivarv=ivarv + 1
+        ierr = putvar(ncoutv, id_varoutv(ivarv), SNGL(dcumulv(:,:)      /ntframe), jk, npiglo, npjglo, kwght=ntframe )
+        ivarv=ivarv + 1
+        ierr = putvar(ncoutv, id_varoutv(ivarv), SNGL(dcumulv2(:,:)     /ntframe), jk, npiglo, npjglo, kwght=ntframe )
+     ENDIF
+
+     !    W
+     IF ( lwo ) THEN
+        DO jsig=1,ndep
+           ivarw=ivarw + 1
+           ierr = putvar(ncoutw, id_varoutw(ivarw), SNGL(dcumulws(:,:,jsig)/ntframe), jk, npiglo, npjglo, kwght=ntframe )
+           IF (lsigo) THEN 
+              ivarw=ivarw + 1
+              ierr = putvar(ncoutw, id_varoutw(ivarw), SNGL(dcumulsw(:,:,jsig)/ntframe), jk, npiglo, npjglo, kwght=ntframe )
+           ENDIF
+        ENDDO
+        IF ( luvo ) THEN 
+           ivarw=ivarw + 1
+           ierr = putvar(ncoutw, id_varoutw(ivarw), SNGL(dcumulw(:,:)      /ntframe), jk, npiglo, npjglo, kwght=ntframe )
+           ivarw=ivarw + 1
+           ierr = putvar(ncoutw, id_varoutw(ivarw), SNGL(dcumulw2(:,:)     /ntframe), jk, npiglo, npjglo, kwght=ntframe )
+        ENDIF
+     ENDIF
+
+     IF ( lcaltmean )  THEN
+        timean(1) = dtotal_time/ntframe
+        ierr      = putvar1d(ncoutu, timean, 1, 'T')
+        ierr      = putvar1d(ncoutv, timean, 1, 'T')
+        IF ( lwo ) ierr = putvar1d(ncoutw, timean, 1, 'T')
+     END IF
+
+     lcaltmean = .FALSE. ! tmean already computed
+
+  END DO  ! loop to next level
+
+  ierr = closeout(ncoutu)
+  ierr = closeout(ncoutv)
+  IF ( lwo ) ierr = closeout(ncoutw)
+
+CONTAINS
+
+  SUBROUTINE CreateOutputFile
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE CreateOutputFile  ***
+    !!
+    !! ** Purpose :  Create netcdf file according to flags
+    !!
+    !! ** Method  :  Flags are global variables and there dore known in
+    !!               in this routine.
+    !!
+    !!----------------------------------------------------------------------
+    INTEGER(KIND=4)    :: jsig, ivaru, ivarv, ivarw
+    CHARACTER(LEN=1)   :: cldep
+    CHARACTER(LEN=256) :: cl_global, cl_refu, cl_refv, cl_refw
+    !!----------------------------------------------------------------------
+    ALLOCATE ( stypvaru(nfieldu), ipku(nfieldu), id_varoutu(nfieldu)    )
+    ALLOCATE ( stypvarv(nfieldv), ipkv(nfieldv), id_varoutv(nfieldv)     )
+    IF ( lwo ) ALLOCATE ( stypvarw(nfieldw), ipkw(nfieldw), id_varoutw(nfieldw)  )
+
+    IF ( lTpt ) THEN
+       cl_global = ' All variables computed on T points'
+       cl_refu= cf_tfil
+       cl_refv= cf_tfil
+       cl_refw= cf_tfil
+    ELSE
+       cl_global = ' All variables on native U or V points'
+       cl_refu= cf_ufil
+       cl_refv= cf_vfil
+       cl_refw= cf_wfil
+    ENDIF
+
+
+    ! define output variables  U points
+    stypvaru%rmissing_value    = 0.
+    stypvaru%valid_min         = -100.
+    stypvaru%valid_max         = 100.
+    stypvaru%conline_operation = 'N/A'
+    stypvaru%caxis             = 'TZYX'
+    ipku(:)= npk  ! all variables (input and output are 3D)
+
+    ivaru=0
+    DO jsig = 1, ndep
+       WRITE(cldep,'(I1)') INT(refdep(jsig)/1000)
+       ivaru = ivaru + 1
+       stypvaru(ivaru)%cname      = 'vousig'//cldep          ; stypvaru(ivaru)%cunits    = 'kg.m-2.s-1'
+       stypvaru(ivaru)%clong_name = 'Mean U x sigma'//cldep  ; stypvaru(ivaru)%cshort_name   = 'vousig'//cldep
+
+       IF ( lsigo ) THEN
+          ivaru = ivaru + 1 
+          stypvaru(ivaru)%cname      = 'vosigu'//cldep              ; stypvaru(ivaru)%cunits  = 'kg.m-3'
+          stypvaru(ivaru)%clong_name = 'Mean sigma'//cldep//' at U' ; stypvaru(ivaru)%cshort_name = 'vosigu'//cldep
+       ENDIF
+    ENDDO
+
+    IF ( luvo ) THEN
+       ivaru = ivaru + 1 
+       stypvaru(ivaru)%cname      = cn_vozocrtx      ; stypvaru(ivaru)%cunits        = 'm/s'
+       stypvaru(ivaru)%clong_name = 'Mean zonal vel' ; stypvaru(ivaru)%cshort_name   = cn_vozocrtx
+       ivaru = ivaru + 1 
+       stypvaru(ivaru)%cname      = TRIM(cn_vozocrtx)//'_sqd'      ; stypvaru(ivaru)%cunits        = '(m/s)^2'
+       stypvaru(ivaru)%clong_name = 'Mean zonal vel squared' ; stypvaru(ivaru)%cshort_name   = TRIM(cn_vozocrtx)//'_sqd' 
+    ENDIF
+
+    ! create output fileset
+    ncoutu = create      (cf_outu, cl_refu,  npiglo, npjglo, npk        )
+    ierr   = createvar   (ncoutu,  stypvaru, nfieldu,      ipku,   id_varoutu , cdglobal=cl_global)
+    ierr   = putheadervar(ncoutu,  cl_refu,  npiglo, npjglo, npk        )
+
+
+    ! define output variables  V points
+    stypvarv%rmissing_value    = 0.
+    stypvarv%valid_min         = -100.
+    stypvarv%valid_max         = 100.
+    stypvarv%conline_operation = 'N/A'
+    stypvarv%caxis             = 'TZYX'
+    ipkv(:)= npk  !   "                     "
+
+    ivarv=0
+    DO jsig = 1, ndep 
+       WRITE(cldep,'(I1)') INT(refdep(jsig)/1000)
+       ivarv = ivarv + 1
+       stypvarv(ivarv)%cname      = 'vovsig'//cldep          ; stypvarv(ivarv)%cunits      = 'kg.m-2.s-1'
+       stypvarv(ivarv)%clong_name = 'Mean V x sigma'//cldep  ; stypvarv(ivarv)%cshort_name = 'vovsig'//cldep
+
+       IF ( lsigo ) THEN
+          ivarv = ivarv + 1
+          stypvarv(ivarv)%cname      = 'vosigv'//cldep              ; stypvarv(ivarv)%cunits      = 'kg.m-3'
+          stypvarv(ivarv)%clong_name = 'Mean sigma'//cldep//' at V' ; stypvarv(ivarv)%cshort_name = 'vosigv'//cldep
+       ENDIF
+    ENDDO
+
+    IF ( luvo ) THEN
+       ivarv = ivarv + 1 
+       stypvarv(ivarv)%cname      = cn_vomecrty      ; stypvarv(ivarv)%cunits        = 'm/s'
+       stypvarv(ivarv)%clong_name = 'Mean merid vel' ; stypvarv(ivarv)%cshort_name   = cn_vomecrty
+       ivarv = ivarv + 1 
+       stypvarv(ivarv)%cname      = TRIM(cn_vomecrty)//'_sqd'      ; stypvarv(ivarv)%cunits  = '(m/s)^2'
+       stypvarv(ivarv)%clong_name = 'Mean merid vel squared' ; stypvarv(ivarv)%cshort_name   = TRIM(cn_vomecrty)//'_sqd'
+    ENDIF
+
+    ncoutv = create      (cf_outv, cl_refv,  npiglo, npjglo, npk        )
+    ierr   = createvar   (ncoutv,  stypvarv, nfieldv,      ipkv,   id_varoutv, cdglobal=cl_global )
+    ierr   = putheadervar(ncoutv,  cl_refv,  npiglo, npjglo, npk        )
+
+    IF ( lwo ) THEN
+       ! define output variables  W points
+       stypvarw%rmissing_value    = 0.
+       stypvarw%valid_min         = -100.
+       stypvarw%valid_max         = 100.
+       stypvarw%conline_operation = 'N/A'
+       stypvarw%caxis             = 'TZYX'
+       ipkw(:)= npk  !   "                     "
+
+       ivarw=0
+       DO jsig = 1, ndep
+          WRITE(cldep,'(I1)') INT(refdep(jsig)/1000)
+          ivarw = ivarw + 1
+          stypvarw(ivarw)%cname      = 'vowsig'//cldep          ; stypvarw(ivarw)%cunits      = 'kg.m-2.s-1'
+          stypvarw(ivarw)%clong_name = 'Mean W x sigma'//cldep  ; stypvarw(ivarw)%cshort_name = 'vowsig'//cldep
+
+          IF ( lsigo ) THEN
+             ivarw = ivarw + 1
+             stypvarw(ivarw)%cname      = 'vosigw'//cldep              ; stypvarw(ivarw)%cunits      = 'kg.m-3'
+             stypvarw(ivarw)%clong_name = 'Mean sigma'//cldep//' at W' ; stypvarw(ivarw)%cshort_name = 'vosigw'//cldep
+          ENDIF
+       ENDDO
+
+       IF ( luvo ) THEN
+          ivarw = ivarw + 1
+          stypvarw(ivarw)%cname      = cn_vovecrtz      ; stypvarw(ivarw)%cunits        = 'm/s'
+          stypvarw(ivarw)%clong_name = 'Mean vert. vel' ; stypvarw(ivarw)%cshort_name   = cn_vovecrtz
+          ivarw = ivarw + 1
+          stypvarw(ivarw)%cname      = TRIM(cn_vovecrtz)//'_sqd' ; stypvarw(ivarw)%cunits       = '(m/s)^2'
+          stypvarw(ivarw)%clong_name = 'Mean vert. vel squared' ; stypvarw(ivarw)%cshort_name   = TRIM(cn_vovecrtz)//'_sqd'
+       ENDIF
+
+       ncoutw = create      (cf_outw, cl_refw,  npiglo, npjglo, npk        )
+       ierr   = createvar   (ncoutw,  stypvarw, nfieldw,      ipku,   id_varoutw, cdglobal=cl_global )
+       ierr   = putheadervar(ncoutw,  cl_refw,  npiglo, npjglo, npk        )
+    ENDIF
+
+
+  END SUBROUTINE  CreateOutputFile
+
+  SUBROUTINE ParseRefDep (cdum)
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE ParseRefDep  ***
+    !!
+    !! ** Purpose :  Decode variable name  option from command line
+    !!
+    !! ** Method  :  look for , in the argument string and set the number of
+    !!         ref_dep (ndep), allocate  array and fill it with the
+    !!         decoded  names.
+    !!
+    !!----------------------------------------------------------------------
+    CHARACTER(LEN=*), INTENT(in) :: cdum
+
+    CHARACTER(LEN=80), DIMENSION(100) :: cl_dum  ! 100 is arbitrary
+    INTEGER  :: ji
+    INTEGER  :: inchar,  i1=1
+    !!----------------------------------------------------------------------
+    inchar= LEN(TRIM(cdum))
+    ndep = 1
+    ! scan the input string and look for ',' as separator
+    DO ji=1,inchar
+       IF ( cdum(ji:ji) == ',' ) THEN
+          cl_dum(ndep) = cdum(i1:ji-1)
+          i1=ji+1
+          ndep=ndep+1
+       ENDIF
+    ENDDO
+
+    ! last name of the list does not have a ','
+    cl_dum(ndep) = cdum(i1:inchar)
+
+    ALLOCATE ( refdep(ndep) )
+    DO ji=1, ndep
+       READ(cl_dum(ji),*) refdep(ji)
+    ENDDO
+    PRINT *, refdep
+  END SUBROUTINE ParseRefDep
+
+
+END PROGRAM cdfvsig
diff --git a/cdfvtrp.f90 b/src/cdfvtrp.f90
similarity index 100%
rename from cdfvtrp.f90
rename to src/cdfvtrp.f90
diff --git a/cdfw.f90 b/src/cdfw.f90
similarity index 100%
rename from cdfw.f90
rename to src/cdfw.f90
diff --git a/cdfweight.f90 b/src/cdfweight.f90
similarity index 100%
rename from cdfweight.f90
rename to src/cdfweight.f90
diff --git a/cdfwflx.f90 b/src/cdfwflx.f90
similarity index 100%
rename from cdfwflx.f90
rename to src/cdfwflx.f90
diff --git a/cdfwhereij.f90 b/src/cdfwhereij.f90
similarity index 100%
rename from cdfwhereij.f90
rename to src/cdfwhereij.f90
diff --git a/cdfzisot.f90 b/src/cdfzisot.f90
similarity index 98%
rename from cdfzisot.f90
rename to src/cdfzisot.f90
index 11b7856..8eb2150 100644
--- a/cdfzisot.f90
+++ b/src/cdfzisot.f90
@@ -168,6 +168,7 @@ PROGRAM cdfzisot
 
         ! read temperature on x-z slab
         rtemxz(:,:) = getvarxz(cf_tfil, cn_votemper, jj, npiglo, npk, kimin=1, kkmin=1, ktime=jt )
+        
 
         ! loop on X axis
         DO ji = 1, npiglo
@@ -199,7 +200,7 @@ PROGRAM cdfzisot
                  ! then start from the first level with T >= rtref
                  ! and search first value below rtref
                  jref = 0
-                 DO WHILE ( jk < npk .AND. rtemxz(ji,jk) > rtref .AND. rtemxz(ji,jk) .NE. rmisval )
+                 DO WHILE ( jk < npk .AND. rtemxz(ji,jk) >= rtref .AND. rtemxz(ji,jk) .NE. rmisval )
                     jref = jk
                     jk = jk + 1
                  ENDDO
diff --git a/cdfzonalmean.f90 b/src/cdfzonalmean.f90
similarity index 69%
rename from cdfzonalmean.f90
rename to src/cdfzonalmean.f90
index 512cc5c..0e4e6d2 100644
--- a/cdfzonalmean.f90
+++ b/src/cdfzonalmean.f90
@@ -32,13 +32,16 @@ PROGRAM cdfzonalmean
   INTEGER(KIND=4)                               :: npiglo, npjglo      ! size of the domain
   INTEGER(KIND=4)                               :: npk, npt            ! size of the domain
   INTEGER(KIND=4)                               :: nvarin, nvar        ! number of input variables: all/valid
+  INTEGER(KIND=4)                               :: nvarmx              ! number of output variables: all/valid
+  INTEGER(KIND=4)                               :: nvaro=1             ! number of output variables: all/valid
+  INTEGER(KIND=4)                               :: ncoef=1             ! 1 or 2 (regarding lmax option) 
   INTEGER(KIND=4)                               :: ncout               ! ncid of output file
   INTEGER(KIND=4)                               :: ierr, ik            ! working integers
   INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: ipki, id_varin      ! jpbasin x nvar
   INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: ipko, id_varout     ! jpbasin x nvar
   INTEGER(KIND=4), DIMENSION(2)                 :: ijloc               ! working array for maxloc
 
-  REAL(KIND=4)                                  :: zspval=99999.       ! missing value 
+  REAL(KIND=4)                                  :: zspval=0.           ! missing value 
   REAL(KIND=4), DIMENSION (:),      ALLOCATABLE :: tim                 ! time counter
   REAL(KIND=4), DIMENSION (:),      ALLOCATABLE :: gdep                ! gdept or gdepw
   REAL(KIND=4), DIMENSION (:,:),    ALLOCATABLE :: e1, e2, gphi, zv    ! metrics, latitude, data value
@@ -46,8 +49,12 @@ PROGRAM cdfzonalmean
   REAL(KIND=4), DIMENSION (:,:),    ALLOCATABLE :: zdumlat             ! latitude for i = north pole
   REAL(KIND=4), DIMENSION (:,:),    ALLOCATABLE :: zmaskvar            ! variable mask
   REAL(KIND=4), DIMENSION (:,:,:),  ALLOCATABLE :: zmask               ! basin mask jpbasins x npiglo x npjglo
+  REAL(KIND=4), DIMENSION (:,:),    ALLOCATABLE :: rzomax              ! zonal maximum
+  REAL(KIND=4), DIMENSION (:,:),    ALLOCATABLE :: rzomin              ! zonal minimum
 
-  REAL(KIND=8), DIMENSION (:,:),    ALLOCATABLE :: dzomean , darea     ! jpbasins x npjglo x npk
+  REAL(KIND=8)                                  :: dtmp                ! temporary variable
+  REAL(KIND=8), DIMENSION (:,:),    ALLOCATABLE :: dzomean , darea     !  npjglo x npk
+  REAL(KIND=8), DIMENSION (:,:),    ALLOCATABLE :: dl_surf             ! surface of cells
 
   CHARACTER(LEN=256)                            :: cf_in               ! input file name
   CHARACTER(LEN=256)                            :: cf_out='zonalmean.nc' ! output file name
@@ -60,6 +67,7 @@ PROGRAM cdfzonalmean
   CHARACTER(LEN=256)                            :: ctyp                ! variable type on C-grid
   CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_namesi           ! input variable names
   CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_nameso           ! output variable names
+  CHARACTER(LEN=80 ), DIMENSION(:), ALLOCATABLE :: cv_fix              ! name of the specified variable to process (-var option)
   CHARACTER(LEN=4  ), DIMENSION(5)              :: cbasin=(/'_glo','_atl','_inp','_ind','_pac'/) ! sub basin suffixes
 
   TYPE(variable), DIMENSION(:),     ALLOCATABLE :: stypvari            ! structure for input variables
@@ -67,21 +75,25 @@ PROGRAM cdfzonalmean
 
   LOGICAL                                       :: lpdep    =.FALSE.   ! flag for depth sign (default dep < 0)
   LOGICAL                                       :: lndep_in =.FALSE.   ! flag for depth sign (default dep < 0) in input file
+  LOGICAL                                       :: lmax     =.FALSE.   ! flag for zonal maximum determination
+  LOGICAL                                       :: lvar     =.FALSE.   ! flag for single variable processing
   LOGICAL                                       :: ldebug   =.FALSE.   ! flag for activated debug print 
   LOGICAL                                       :: l2d      =.FALSE.   ! flag for 2D files
   LOGICAL                                       :: lchk     =.FALSE.   ! flag for missing files
+  LOGICAL, DIMENSION(:),            ALLOCATABLE :: lbad                ! flag array for variable selection
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
   narg= iargc()
   IF ( narg == 0 ) THEN
-     PRINT *,' usage : cdfzonalmean IN-file point_type [ BASIN-file] ...'
-     PRINT *,'                  ... [-pdep | --positive_depths]'
+     PRINT *,' usage : cdfzonalmean IN-file point_type [ BASIN-file] [-debug]...'
+     PRINT *,'       ...[-var var1,var2,..] [-max ] [-pdep | --positive_depths]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
      PRINT *,'       Compute the zonal mean of all the variables available in the' 
      PRINT *,'       input file. This program assume that all the variables are'
      PRINT *,'       located on the same C-grid point, specified on the command line.'
+     PRINT *,'         Using -var option limits the variables to be processed.'
      PRINT *,'      '
      PRINT *,'       Zonal mean is in fact the mean value computed along the I coordinate.'
      PRINT *,'       The result is a vertical slice, in the meridional direction.'
@@ -97,6 +109,8 @@ PROGRAM cdfzonalmean
      PRINT *,'       [BASIN-file] : netcdf file describing sub basins, similar to '
      PRINT *,'                      ', TRIM(cn_fbasins),'. If this name is not given '
      PRINT *,'                      as option, only the global zonal mean is computed.'
+     PRINT *,'       [-max     ] : output the zonal maximum and minimum of the variable '
+     PRINT *,'       [-var var1,var2,.. ] : Comma separated list of selected variables'
      PRINT *,'       [-pdep | --positive_depths ] : use positive depths in the output file.'
      PRINT *,'                      Default behaviour is to have negative depths.'
      PRINT *,'       [-ndep_in ] : negative depths are used in the input file.'
@@ -113,6 +127,8 @@ PROGRAM cdfzonalmean
      PRINT *,'                      where zo replace vo/so prefix of the input variable'
      PRINT *,'                      where bas is a suffix for each sub-basins (or glo)'
      PRINT *,'                      if a BASIN-file is used.'
+     PRINT *,'                 If option -max is used, each standard output variable'
+     PRINT *,'                     is associated with a var_max variable.'
      STOP
   ENDIF
 
@@ -123,6 +139,10 @@ PROGRAM cdfzonalmean
     CASE ( '-pdep' , '--positive_depths' ) ; lpdep    =.TRUE.
     CASE ( '-ndep_in'                    ) ; lndep_in =.TRUE.
     CASE ( '-debug'                      ) ; ldebug   =.TRUE.
+    CASE ( '-max'                        ) ; lmax     =.TRUE. ; ncoef=3
+    CASE ( '-var'                        ) ; lvar     =.TRUE.
+                                             CALL getarg( ijarg, cldum) ; ijarg=ijarg+1
+                                             CALL ParseVars(cldum) 
     CASE DEFAULT
       ireq=ireq+1
       SELECT CASE (ireq)
@@ -137,6 +157,15 @@ PROGRAM cdfzonalmean
     END SELECT
   END DO
 
+  IF ( ldebug ) THEN  ! additional print for debuging
+     PRINT *,' Option -pdep     ', lpdep
+     PRINT *,' Option -npdep_in ', lndep_in
+     PRINT *,' Option -debug    ', ldebug
+     PRINT *,' Option -max      ', lmax
+     PRINT *,' Option -var      ', lvar
+     PRINT *,' NPBASINS       = ', npbasins
+  ENDIF
+
   ! check  files existence
   lchk = lchk .OR. chkfile (cn_fhgr)
   lchk = lchk .OR. chkfile (cn_fzgr)
@@ -170,14 +199,36 @@ PROGRAM cdfzonalmean
      PRINT *, ' C grid:', TRIM(ctyp),' point not known!' ; STOP
   END SELECT
 
-  nvarin  = getnvar(cf_in)   ! number of input variables
-  ALLOCATE ( cv_namesi(nvarin),          ipki(nvarin),          id_varin (nvarin)          )
-  ALLOCATE ( cv_nameso(npbasins*nvarin), ipko(npbasins*nvarin), id_varout(npbasins*nvarin) )
-  ALLOCATE ( stypvari(nvarin)                                                              )
-  ALLOCATE ( stypvaro(npbasins*nvarin)                                                     )
+  nvarin  = getnvar(cf_in)   ! number of input variables in file
+  IF ( .NOT. lvar ) THEN
+    nvaro = nvarin
+  ENDIF
+
+  nvarmx = ncoef * npbasins * nvaro
+
+  IF ( ldebug ) PRINT *,' NVARMX (output) :', nvarmx
+
+  ALLOCATE ( cv_namesi(nvarin), ipki(nvarin), id_varin (nvarin) )
+  ALLOCATE ( cv_nameso(nvarmx), ipko(nvarmx), id_varout(nvarmx) )
+  ALLOCATE ( stypvari(nvarin)                                   )
+  ALLOCATE ( stypvaro(nvarmx)                                   )
 
   cv_namesi(1:nvarin) = getvarname(cf_in, nvarin, stypvari )
   ipki     (1:nvarin) = getipk    (cf_in, nvarin           )
+ 
+  IF ( lvar )  THEN 
+     ALLOCATE ( lbad(nvarin) ) 
+     lbad(:) = .true.  ! 
+     ! tricks : in case of specified variables, set ipki to 0 all variables
+     !          not choosen.
+     DO ji = 1, nvaro
+       DO jvar = 1, nvarin
+         IF ( cv_namesi(jvar) == cv_fix(ji) ) lbad(jvar) = .false.
+       END DO
+     END DO
+     WHERE ( lbad ) ipki=0
+     DEALLOCATE (lbad )
+  ENDIF
 
   ! buildt output filename
   nvar = 0  ! over all number of valid variables for zonal mean ( < nvarin)
@@ -223,6 +274,21 @@ PROGRAM cdfzonalmean
      ENDIF
   END DO
 
+  nvaro = ivar  ! total number of output variables
+  IF ( lmax ) THEN  ! create variable and entry for zonal max
+     DO jvar = 1,nvaro
+       stypvaro(jvar+nvaro) = stypvaro(jvar)  ! copy all var attributes 
+       ipko    (jvar+nvaro) = ipko    (jvar)
+       stypvaro(jvar+nvaro)%cname      = TRIM(stypvaro (jvar)%cname)//'_max'
+       stypvaro(jvar+nvaro)%clong_name = 'Zonal_Max_'//TRIM(stypvaro (jvar)%clong_name(12:))
+
+       stypvaro(jvar+2*nvaro) = stypvaro(jvar)  ! copy all var attributes 
+       ipko    (jvar+2*nvaro) = ipko    (jvar)
+       stypvaro(jvar+2*nvaro)%cname      = TRIM(stypvaro (jvar)%cname)//'_min'
+       stypvaro(jvar+2*nvaro)%clong_name = 'Zonal_Min_'//TRIM(stypvaro (jvar)%clong_name(12:))
+     ENDDO
+  ENDIF
+
   npiglo = getdim (cf_in, cn_x)
   npjglo = getdim (cf_in, cn_y)
   npk    = getdim (cf_in, cn_z)
@@ -245,13 +311,17 @@ PROGRAM cdfzonalmean
   ALLOCATE ( e1(npiglo,npjglo), e2      (npiglo,npjglo) )
   ALLOCATE ( gphi(npiglo,npjglo), gdep(npk), tim(npt)   )
   ALLOCATE ( zdumlon(1,npjglo), zdumlat(1,npjglo)       )
+  IF ( lmax ) ALLOCATE ( rzomax(npjglo,npk)             )
+  IF ( lmax ) ALLOCATE ( rzomin(npjglo,npk)             )
   ALLOCATE ( dzomean(npjglo,npk), darea(npjglo,npk)     )
-
+  ALLOCATE ( dl_surf(npiglo,npjglo)                     )
 
   ! get the metrics
   e1(:,:)   = getvar(cn_fhgr, cv_e1,  1, npiglo, npjglo) 
   e2(:,:)   = getvar(cn_fhgr, cv_e2,  1, npiglo, npjglo) 
   gphi(:,:) = getvar(cn_fhgr, cv_phi, 1, npiglo, npjglo)
+  
+  dl_surf(:,:) = 1.d0 * e1(:,:) * e2(:,:)
 
   IF (l2d)  THEN 
      gdep(:) = 0
@@ -269,9 +339,9 @@ PROGRAM cdfzonalmean
   zdumlon(:,:) = 0.              ! set the dummy longitude to 0
 
   ! create output fileset
-  ncout = create      (cf_out, cf_in,    1,    npjglo, npk,  cdep=cv_depo                                )
-  ierr  = createvar   (ncout,  stypvaro, ivar, ipko,   id_varout                                         )
-  ierr  = putheadervar(ncout,  cf_in,    1,    npjglo, npk,  pnavlon=zdumlon, pnavlat=zdumlat, pdep=gdep )
+  ncout = create      (cf_out, cf_in,    1,           npjglo, npk,  cdep=cv_depo                                )
+  ierr  = createvar   (ncout,  stypvaro, ncoef*nvaro, ipko,   id_varout                                         )
+  ierr  = putheadervar(ncout,  cf_in,    1,           npjglo, npk,  pnavlon=zdumlon, pnavlat=zdumlat, pdep=gdep )
 
   tim   = getvar1d(cf_in, cn_vtimec, npt     )
   ierr  = putvar1d(ncout, tim,       npt, 'T')
@@ -307,12 +377,20 @@ PROGRAM cdfzonalmean
               dzomean(:,:) = 0.d0
               darea(:,:)   = 0.d0
               ! integrates 'zonally' (along i-coordinate)
-              DO ji=1,npiglo
-                 DO jj=1,npjglo
-                    dzomean(jj,jk) = dzomean(jj,jk) + 1.d0*e1(ji,jj)*e2(ji,jj)* zmask(jbasin,ji,jj)*zmaskvar(ji,jj)*zv(ji,jj)
-                    darea(jj,jk)   = darea(jj,jk)   + 1.d0*e1(ji,jj)*e2(ji,jj)* zmask(jbasin,ji,jj)*zmaskvar(ji,jj)
+              IF ( lmax) rzomax(:,jk) = -1.e20
+              IF ( lmax) rzomin(:,jk) =  1.e20
+
+              !$OMP PARALLEL DO SCHEDULE(RUNTIME) PRIVATE(dtmp)
+              DO jj=1,npjglo
+                  DO ji=1,npiglo
+                    dtmp = 1.d0 * zmask(jbasin,ji,jj)*zmaskvar(ji,jj)*zv(ji,jj)
+                    dzomean(jj,jk) = dzomean(jj,jk) + dl_surf(ji,jj)* dtmp
+                    darea  (jj,jk) = darea  (jj,jk) + dl_surf(ji,jj)* zmask(jbasin,ji,jj)*zmaskvar(ji,jj)
+           IF( lmax )                 rzomax (jj,jk) = MAX(rzomax (jj,jk), dtmp )
+           IF( lmax .AND. dtmp /= 0.) rzomin (jj,jk) = MIN(rzomin (jj,jk), dtmp )
                  END DO
               END DO
+              !$OMP  END  PARALLEL DO
 
               ! compute the mean value if the darea is not 0, else assign spval
               WHERE (darea /= 0 ) 
@@ -320,13 +398,60 @@ PROGRAM cdfzonalmean
               ELSEWHERE
                  dzomean=zspval
               ENDWHERE
+              IF (lmax)  THEN
+                 WHERE (darea == 0 ) 
+                   rzomax=zspval ; rzomin=zspval 
+                 ENDWHERE
+              ENDIF
+
               ivar = (jvar-1)*npbasins + jbasin
-              ierr = putvar (ncout, id_varout(ivar), REAL(dzomean(:,jk)), jk, 1, npjglo, ktime=jt)
+              ierr = putvar (ncout, id_varout(ivar),   REAL(dzomean(:,jk)), jk, 1, npjglo, ktime=jt)
+   IF ( lmax) ierr = putvar (ncout, id_varout(ivar+nvaro),   rzomax(:,jk),  jk, 1, npjglo, ktime=jt)
+   IF ( lmax) ierr = putvar (ncout, id_varout(ivar+2*nvaro), rzomin(:,jk),  jk, 1, npjglo, ktime=jt)
            END DO  !next basin
         END DO  ! next k 
      END DO ! next time
   END DO ! next variable
 
   ierr = closeout(ncout)
+CONTAINS 
+   SUBROUTINE ParseVars (cdum)
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE ParseVars  ***
+      !!
+      !! ** Purpose :  Decode -var option from command line
+      !!
+      !! ** Method  :  look for , in the argument string and set the number of
+      !!         variable (nvaro), allocate cv_fix array and fill it with the
+      !!         decoded  names.
+      !!
+      !!----------------------------------------------------------------------
+      CHARACTER(LEN=*), INTENT(in) :: cdum
+
+      CHARACTER(LEN=80), DIMENSION(100) :: cl_dum  ! 100 is arbitrary
+      INTEGER  :: ji
+      INTEGER  :: inchar,  i1=1
+      !!----------------------------------------------------------------------
+
+      inchar= LEN(TRIM(cdum))
+      ! scan the input string and look for ',' as separator
+      DO ji=1,inchar
+         IF ( cdum(ji:ji) == ',' ) THEN
+            cl_dum(nvaro) = cdum(i1:ji-1)
+            i1=ji+1
+            nvaro=nvaro+1
+         ENDIF
+      ENDDO
+
+      ! last name of the list does not have a ','
+      cl_dum(nvaro) = cdum(i1:inchar)
+
+      ALLOCATE ( cv_fix(nvaro) )
+      IF ( ldebug) PRINT *,' SELECTED VARIABLES :'
+      DO ji=1, nvaro
+         cv_fix(ji) = cl_dum(ji)
+         IF ( ldebug) PRINT *, "    ",TRIM(cv_fix(ji))
+      ENDDO
+   END SUBROUTINE ParseVars
 
 END PROGRAM cdfzonalmean
diff --git a/src/cdfzonalmeanvT.f90 b/src/cdfzonalmeanvT.f90
new file mode 100644
index 0000000..4da888f
--- /dev/null
+++ b/src/cdfzonalmeanvT.f90
@@ -0,0 +1,354 @@
+PROGRAM cdfzonalmeanvT
+   !!======================================================================
+   !!                     ***  PROGRAM  cdfzonalmeanvT  ***
+   !!=====================================================================
+   !!  ** Purpose : Compute the mean product of zonal mean V by zonal mean
+   !!               of tracer (T and S )
+   !!
+   !!  ** Method  : In this program the 'zonal' meanvT is in fact a meanvT 
+   !!               along the I coordinate. 
+   !! History : 3.0  : 06/2013  : J.M. Molines : from cdfzonalmean and cdfvT
+   !!----------------------------------------------------------------------
+   USE cdfio
+   USE modcdfnames
+   USE modutils
+   !!----------------------------------------------------------------------
+   !! CDFTOOLS_3.0 , MEOM 2011
+   !! $Id$
+   !! Copyright (c) 2011, J.-M. Molines
+   !! Software governed by the CeCILL licence (Licence/CDFTOOLSCeCILL.txt)
+   !!----------------------------------------------------------------------
+   IMPLICIT NONE
+
+   INTEGER(KIND=4)                              :: ji, jj, jk ,jt      ! dummy loop index
+   INTEGER(KIND=4)                              :: jbasin, jtag        ! dummy loop index
+   INTEGER(KIND=4)                              :: npbasins=1          ! number of subbasin
+   INTEGER(KIND=4)                              :: ivar = 0            ! output variable counter
+   INTEGER(KIND=4)                              :: narg, iargc         ! command line 
+   INTEGER(KIND=4)                              :: ijarg, ireq         ! command line 
+   INTEGER(KIND=4)                              :: itag, ntag          ! arg index of 1rst tag, number of tags
+   INTEGER(KIND=4)                              :: ntframe                ! time frame counter
+   INTEGER(KIND=4)                              :: npiglo, npjglo      ! size of the domain
+   INTEGER(KIND=4)                              :: npk, npt            ! size of the domain
+   INTEGER(KIND=4)                              :: ncout               ! ncid of output file
+   INTEGER(KIND=4)                              :: ierr                ! working integers
+   INTEGER(KIND=4), DIMENSION(:),   ALLOCATABLE :: ipk, id_varout      ! jpbasin x nvar
+   INTEGER(KIND=4), DIMENSION(2)                :: ijloc               ! for maxloc
+
+   REAL(KIND=4)                                 :: zspval=99999.       ! missing value 
+   REAL(KIND=4), DIMENSION (:),     ALLOCATABLE :: tim                 ! time counter
+   REAL(KIND=4), DIMENSION (:),     ALLOCATABLE :: gdep                ! gdept or gdepw
+   REAL(KIND=4), DIMENSION (:,:),   ALLOCATABLE :: e1, e2, gphi        ! metrics, latitude
+   REAL(KIND=4), DIMENSION (:,:),   ALLOCATABLE :: ztem, zsal, zvel    ! temp, sal and velocity
+   REAL(KIND=4), DIMENSION (:,:),   ALLOCATABLE :: zdumlon             ! dummy longitude = 0.
+   REAL(KIND=4), DIMENSION (:,:),   ALLOCATABLE :: zdumlat             ! latitude for i = north pole
+   REAL(KIND=4), DIMENSION (:,:),   ALLOCATABLE :: zvmask              ! vmask
+   REAL(KIND=4), DIMENSION (:,:,:), ALLOCATABLE :: zmask               ! basin mask jpbasins x npiglo x npjglo
+
+   REAL(KIND=8)                                 :: dtotal_time         ! cumul of time in seconds
+   REAL(KIND=8), DIMENSION (:),     ALLOCATABLE :: dzovel, dzotem, dzosal  ! npjglo
+   REAL(KIND=8), DIMENSION (:),     ALLOCATABLE :: darea, dl_tmp       ! npjglo
+   REAL(KIND=8), DIMENSION (:,:,:,:), ALLOCATABLE :: dzovt, dzovs       ! 1xnpjglo x npk x npbasins
+
+   CHARACTER(LEN=256)                           :: cf_tfil, cf_sfil    ! input files names for T S
+   CHARACTER(LEN=256)                           :: cf_vfil             ! input files names for V
+   CHARACTER(LEN=256)                           :: cf_out='zonalmeanvt.nc' ! output file name
+   CHARACTER(LEN=256)                           :: cf_basins='none'    ! sub basin file name
+   CHARACTER(LEN=256)                           :: cldum               ! dummy character variable
+   CHARACTER(LEN=256)                           :: confcase            ! confcase name
+   CHARACTER(LEN=4  ), DIMENSION(5)             :: cbasin=(/'_glo','_atl','_inp','_ind','_pac'/) ! sub basin suffixes
+
+   TYPE(variable), DIMENSION(:),    ALLOCATABLE :: stypvar             ! structure for input variables
+
+   LOGICAL            :: lpdep    =.FALSE.   ! flag for depth sign (default dep < 0)
+   LOGICAL            :: lndep_in =.FALSE.   ! flag for depth sign (default dep < 0) in input file
+   LOGICAL            :: ldebug   =.FALSE.   ! flag for activated debug print 
+   LOGICAL            :: lchk     =.FALSE.   ! flag for missing files
+   !!----------------------------------------------------------------------
+   CALL ReadCdfNames()
+
+   narg= iargc()
+   IF ( narg == 0 ) THEN
+      PRINT *,' usage : cdfzonalmeanvT [-b BASIN-file] [-pdep |--positive_depths] ... '
+      PRINT *,'                   ...  [-ndep_in]   CONFIG-CASE  ''list_of_tags'' '
+      PRINT *,'      '
+      PRINT *,'     PURPOSE :'
+      PRINT *,'       Compute the mean product of zonal mean V by zonal mean of T and S.'
+      PRINT *,'      '
+      PRINT *,'       Zonal mean is in fact the mean value computed along the I coordinate.'
+      PRINT *,'       The result is a vertical slice, in the meridional direction.'
+      PRINT *,'      '
+      PRINT *,'       REMARK : partial step are not handled properly (but probably '
+      PRINT *,'                minor impact on results).'
+      PRINT *,'      '
+      PRINT *,'     ARGUMENTS :'
+      PRINT *,'       CONFIG-CASE is the config name of a given experiment (eg ORCA025-G70)'
+      PRINT *,'            The program will look for gridT, gridU and gridV files for'
+      PRINT *,'            this config ( grid_T, grid_U and grid_V are also accepted).'
+      PRINT *,'            Additionaly, if gridS or grid_S file is found, it will be taken'
+      PRINT *,'            in place of gridT for the salinity variable.'
+      PRINT *,'       list_of_tags : a list of time tags that will be used for time'
+      PRINT *,'            averaging. e.g. y2000m01d05 y2000m01d10 ...'
+      PRINT *,'      '
+      PRINT *,'     OPTIONS :'
+      PRINT *,'       [-b BASIN-file] : netcdf file describing sub basins, similar to '
+      PRINT *,'                      ', TRIM(cn_fbasins),'. If this name is not given '
+      PRINT *,'                      as option, only the global zonal mean is computed.'
+      PRINT *,'       [-pdep | --positive_depths ] : use positive depths in the output file.'
+      PRINT *,'                      Default behaviour is to have negative depths.'
+      PRINT *,'       [-ndep_in ] : negative depths are used in the input file.'
+      PRINT *,'                      Default behaviour is to have positive depths.'
+      PRINT *,'       [-debug   ] : add some print for debug'
+      PRINT *,'      '
+      PRINT *,'     REQUIRED FILES :'
+      PRINT *,'       ',TRIM(cn_fhgr),', ', TRIM(cn_fzgr),' and ', TRIM(cn_fmsk)
+      PRINT *,'      '
+      PRINT *,'     OUTPUT : '
+      PRINT *,'       netcdf file : ', TRIM(cf_out) 
+      PRINT *,'         variables : zovzot : mean product of zonal_mean(V) x zonal_mean(T)'
+      PRINT *,'                     zovzot : mean product of zonal_mean(V) x zonal_mean(S)'
+      PRINT *,'                       A suffix _bas is append to variable name oin order to'
+      PRINT *,'                     indicate the basin (atl, inp, ind, pac) or glo for global'
+      PRINT *,'         '
+      STOP
+   ENDIF
+
+   ! decode command line
+   ijarg = 1  ; ireq = 0
+   DO WHILE ( ijarg <= narg ) 
+      CALL getarg( ijarg, cldum ) ; ijarg=ijarg+1
+      SELECT CASE (cldum)
+      CASE ( '-pdep' , '--positive_depths' ) ; lpdep    =.TRUE.
+      CASE ( '-ndep_in'                    ) ; lndep_in =.TRUE.
+      CASE ( '-debug'                      ) ; ldebug   =.TRUE.
+      CASE ( '-b'                          ) ; CALL getarg( ijarg,cf_basins ) ;  ijarg=ijarg+1 ;  npbasins   = 5
+      CASE DEFAULT
+         ireq=ireq+1
+         SELECT CASE (ireq)
+         CASE (1) ; confcase = cldum                 ! file name is the 1rst argument
+         CASE DEFAULT 
+            itag = ijarg -1
+            ntag = narg - itag + 1
+            EXIT             ! exit while loop after recording number of tags and arg number of 1rst tag
+         END SELECT
+      END SELECT
+   END DO
+
+   IF ( ldebug ) THEN
+      PRINT *, ' CONFIG-CASE = ', TRIM(confcase)
+      PRINT *, ' NTAGS       = ', ntag
+      PRINT *, ' 1rst tag    = ', TRIM(cldum)
+      PRINT *, '  arg pos    = ', itag
+   ENDIF
+
+   ! check  files existence
+   lchk = lchk .OR. chkfile (cn_fhgr)
+   lchk = lchk .OR. chkfile (cn_fzgr)
+   lchk = lchk .OR. chkfile (cn_fmsk)
+   IF ( npbasins /=1 ) THEN
+      lchk = lchk .OR. chkfile (cf_basins  )
+   ENDIF
+   IF ( lchk ) STOP ! missing files
+
+   cf_tfil = SetFileName( confcase, cldum, 'T')  ! look in first T file for dimensions
+   IF ( chkfile (cf_tfil) ) STOP 
+
+   npiglo = getdim (cf_tfil,cn_x)
+   npjglo = getdim (cf_tfil,cn_y)
+   npk    = getdim (cf_tfil,cn_z)
+
+   ! Allocation ...
+   ALLOCATE ( ipk(2*npbasins), id_varout(2*npbasins) )
+   ALLOCATE ( stypvar(2*npbasins) )
+
+   ALLOCATE ( gdep (npk) )
+   ALLOCATE ( e1(npiglo,npjglo), e2(npiglo,npjglo), gphi(npiglo,npjglo) )
+   ALLOCATE ( zvmask(npiglo, npjglo))
+   ALLOCATE ( zvel(npiglo,npjglo), ztem(npiglo,npjglo), zsal(npiglo,npjglo) )
+   ALLOCATE ( zdumlon(1,npjglo), zdumlat(1,npjglo) )
+   ALLOCATE ( zmask(npbasins,npiglo, npjglo))
+
+   ALLOCATE ( dzovel(npjglo), dzotem(npjglo), dzosal(npjglo), darea(npjglo), dl_tmp(npjglo) )
+   ALLOCATE ( dzovt(1,npjglo, npk, npbasins), dzovs(1,npjglo, npk, npbasins) )
+
+   ! read config information previous to file creation
+   gdep(:)   = getvare3(cn_fzgr, cn_gdept, npk)
+   gphi(:,:) = getvar(cn_fhgr, cn_gphit, 1, npiglo, npjglo)
+
+   ! Look for the i-index that go through the North Pole
+   ijloc        = MAXLOC(gphi)
+   zdumlat(1,:) = gphi(ijloc(1),:)  ! 
+   zdumlon(:,:) = 0.                ! set the dummy longitude to 0
+   IF ( .NOT. lpdep ) gdep(:)   = -1.*  gdep(:)     ! helps for plotting the results
+
+   IF ( ldebug ) PRINT *, 'Create Output files ...'
+   CALL CreateOutput
+   IF ( ldebug ) PRINT *, 'done.'
+
+   ! initialization of 2D time independant fields
+   zmask(1,:,:) = getvar(cn_fmsk, 'tmask', 1, npiglo, npjglo)
+   IF ( cf_basins /= 'none' ) THEN
+      zmask(2,:,:) = getvar(cf_basins, 'tmaskatl', 1, npiglo, npjglo )
+      zmask(4,:,:) = getvar(cf_basins, 'tmaskind', 1, npiglo, npjglo )
+      zmask(5,:,:) = getvar(cf_basins, 'tmaskpac', 1, npiglo, npjglo )
+      zmask(3,:,:) = zmask(5,:,:) + zmask(4,:,:)
+      ! ensure that there are no overlapping on the masks
+      WHERE(zmask(3,:,:) > 0 ) zmask(3,:,:) = 1
+   ENDIF
+   e1(:,:)   = getvar(cn_fhgr, cn_ve1v,  1, npiglo, npjglo) 
+   e2(:,:)   = getvar(cn_fhgr, cn_ve2v,  1, npiglo, npjglo) 
+
+   ! tag loop
+   ijarg = itag
+   ntframe  = 0  ! reset count index for time mean
+
+   DO jtag = 1, ntag 
+      CALL getarg ( ijarg, cldum ) ; ijarg = ijarg + 1
+      cf_tfil = SetFileName( confcase, cldum, 'T', ld_stop=.TRUE.  )
+      cf_sfil = SetFileName( confcase, cldum, 'S', ld_stop=.FALSE. )
+      cf_vfil = SetFileName( confcase, cldum, 'V'                  )
+      IF ( chkfile (cf_sfil, ld_verbose=.FALSE.) ) cf_sfil = cf_tfil  ! do not complain if not found
+      IF ( ldebug ) THEN
+         PRINT *, ' T-FILE = ', TRIM(cf_tfil)
+         PRINT *, ' S-FILE = ', TRIM(cf_sfil)
+         PRINT *, ' V-FILE = ', TRIM(cf_vfil)
+      ENDIF
+
+      npt = getdim (cf_tfil,cn_t)   ! case of multiple time frames in a single file, assume identical of V file
+      ALLOCATE( tim(npt) ) 
+      tim = getvar1d(cf_tfil, cn_vtimec, npt)
+      IF ( ldebug ) PRINT *, 'TIME : ', tim(:)
+      dtotal_time = dtotal_time + SUM(tim(1:npt) )
+      DEALLOCATE( tim )
+      dzovt = 0.d0
+      dzovs = 0.d0
+
+      DO jt = 1, npt  
+         ntframe = ntframe + 1
+         DO jk = 1, npk 
+            IF ( ldebug) PRINT *,' JTAG JT JK', jtag, jt, jk
+            ! read variables 
+            zsal(:,:) = getvar(cf_sfil,  cn_vosaline, jk, npiglo, npjglo, ktime=jt )
+            ztem(:,:) = getvar(cf_tfil,  cn_votemper, jk, npiglo, npjglo, ktime=jt )
+            zvel(:,:) = getvar(cf_vfil,  cn_vomecrty, jk, npiglo, npjglo, ktime=jt )
+            ! do not read e3 metrics at level jk ( to do as in cdfzonal mean ... JMM : to be improved !
+            zvmask(:,:) = getvar(cn_fmsk, 'vmask',    jk ,npiglo, npjglo          )
+
+            ! put T and S at V points
+            ztem(:,1:npjglo-1) = 0.5 * ( ztem(:,1:npjglo-1) + ztem(:,2:npjglo) ) * zvmask(:,1:npjglo-1)
+            zsal(:,1:npjglo-1) = 0.5 * ( zsal(:,1:npjglo-1) + zsal(:,2:npjglo) ) * zvmask(:,1:npjglo-1)
+
+            ! For all basins 
+            DO jbasin = 1, npbasins
+            IF ( ldebug) PRINT *,'    JBASIN ', jbasin
+               dzovel(:) = 0.d0
+               dzotem(:) = 0.d0
+               dzosal(:) = 0.d0
+               darea (:) = 0.d0
+            IF ( ldebug) PRINT *,'      reset done.'
+
+               ! integrates V 'zonally' (along i-coordinate)
+               DO ji=1,npiglo
+                  dl_tmp(:) = 1.d0*e1(ji,:)*e2(ji,:)* zmask(jbasin,ji,:) 
+                  dzovel(:) = dzovel(:) + dl_tmp(:)*zvel  (ji,:)
+                  dzotem(:) = dzotem(:) + dl_tmp(:)*ztem  (ji,:)
+                  dzosal(:) = dzosal(:) + dl_tmp(:)*zsal  (ji,:)
+                  darea (:) = darea (:) + dl_tmp(:)*zvmask(ji,:)
+               END DO
+            IF ( ldebug) PRINT *,'      Zonal integral done.'
+
+               ! compute the mean value if the darea is not 0, else assign spval
+               WHERE (darea /= 0 )
+                  dzovel=dzovel/darea
+                  dzotem=dzotem/darea
+                  dzosal=dzosal/darea
+                  ! cumulate in time
+                  dzovt(1,:,jk,jbasin) = dzovt(1,:,jk,jbasin) + dzovel(:)*dzotem(:)
+                  dzovs(1,:,jk,jbasin) = dzovs(1,:,jk,jbasin) + dzovel(:)*dzosal(:)
+               ELSEWHERE
+                  dzovel=zspval
+                  dzotem=zspval
+                  dzosal=zspval
+                  ! cumulate in time
+                  dzovt(1,:,jk,jbasin) = zspval
+                  dzovs(1,:,jk,jbasin) = zspval
+               ENDWHERE
+            IF ( ldebug) PRINT *,'      mean and masking done.'
+
+            END DO  !next basin
+         END DO ! next level
+      ENDDO   ! next time in file
+   ENDDO  ! next file
+
+   ! normalize before output
+   WHERE ( dzovt /= zspval ) 
+      dzovt(:,:,:,:) = dzovt(:,:,:,:) / ntframe
+      dzovs(:,:,:,:) = dzovs(:,:,:,:) / ntframe
+   ELSEWHERE
+      dzovt(:,:,:,:) = zspval
+      dzovs(:,:,:,:) = zspval
+   ENDWHERE
+
+   ALLOCATE ( tim(1) )
+   tim(1) = dtotal_time/ntframe
+   IF ( ldebug ) PRINT *, ' mean time ', tim(1), ntframe
+
+   ! output file 
+   ierr   = putvar1d(ncout, tim, 1, 'T')
+   ivar = 0
+   DO jbasin = 1, npbasins
+      ivar = ivar + 1
+      DO jk = 1, npk
+         ierr = putvar (ncout, id_varout(ivar  ), REAL(dzovt(:,:,jk,jbasin) ), jk, 1, npjglo, kwght=ntframe )
+         ierr = putvar (ncout, id_varout(ivar+1), REAL(dzovs(:,:,jk,jbasin) ), jk, 1, npjglo, kwght=ntframe )
+      ENDDO
+      ivar = ivar + 1
+   ENDDO
+
+   ierr = closeout(ncout)
+
+CONTAINS 
+   SUBROUTINE CreateOutput
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE CreateOutput  ***
+      !!
+      !! ** Purpose :  Set up all things required for the output file, create
+      !!               the file and write the header part.
+      !!
+      !! ** Method  :  Use global module variables
+      !!
+      !!----------------------------------------------------------------------
+      ipk(:) = npk
+      ivar = 0
+      DO jbasin = 1, npbasins
+         ivar = ivar + 1
+         stypvar(ivar)%cname             = 'zovzot'//TRIM(cbasin(jbasin) )
+         stypvar(ivar)%cunits            = 'm.DegC.s-1'
+         stypvar(ivar)%rmissing_value    = zspval
+         stypvar(ivar)%valid_min         = -50.
+         stypvar(ivar)%valid_max         =  50.
+         stypvar(ivar)%clong_name        = 'product of zonalmean V x zonalmean T for'//TRIM(cbasin(jbasin) )
+         stypvar(ivar)%cshort_name       = 'zovzot'//TRIM(cbasin(jbasin) )
+         stypvar(ivar)%conline_operation = 'N/A'
+         stypvar(ivar)%caxis             = 'TZY'
+
+         ivar = ivar + 1
+         stypvar(ivar)%cname             = 'zovzos'//TRIM(cbasin(jbasin) )
+         stypvar(ivar)%cunits            = 'm.PSU.s-1'
+         stypvar(ivar)%rmissing_value    = zspval
+         stypvar(ivar)%valid_min         = -50.
+         stypvar(ivar)%valid_max         = 50.
+         stypvar(ivar)%clong_name        = 'product of zonalmean V x zonalmean S for'//TRIM(cbasin(jbasin) )
+         stypvar(ivar)%cshort_name       = 'zovzos'//TRIM(cbasin(jbasin) )
+         stypvar(ivar)%conline_operation = 'N/A'
+         stypvar(ivar)%caxis             = 'TZY'
+      END DO
+
+      ! create output fileset
+      ncout = create      (cf_out, cf_tfil,          1, npjglo, npk    )
+      ierr  = createvar   (ncout,  stypvar, 2*npbasins, ipk, id_varout )
+      ierr  = putheadervar(ncout,  cf_tfil,          1, npjglo, npk, pnavlon=zdumlon, pnavlat=zdumlat, pdep=gdep )
+
+   END SUBROUTINE CreateOutput
+
+END PROGRAM cdfzonalmeanvT
diff --git a/cdfzonalout.f90 b/src/cdfzonalout.f90
similarity index 100%
rename from cdfzonalout.f90
rename to src/cdfzonalout.f90
diff --git a/cdfzonalsum.f90 b/src/cdfzonalsum.f90
similarity index 81%
rename from cdfzonalsum.f90
rename to src/cdfzonalsum.f90
index 858809a..bcdd522 100644
--- a/cdfzonalsum.f90
+++ b/src/cdfzonalsum.f90
@@ -32,6 +32,8 @@ PROGRAM cdfzonalsum
   INTEGER(KIND=4)                               :: npiglo, npjglo      ! size of the domain
   INTEGER(KIND=4)                               :: npk, npt            ! size of the domain
   INTEGER(KIND=4)                               :: nvarin, nvar        ! number of input variables: all/valid
+  INTEGER(KIND=4)                               :: nvarmx              ! number of output variables: all/valid
+  INTEGER(KIND=4)                               :: nvaro=1             ! number of output variables: all/valid
   INTEGER(KIND=4)                               :: ncout               ! ncid of output file
   INTEGER(KIND=4)                               :: ierr                ! working integer
   INTEGER(KIND=4), DIMENSION(:),    ALLOCATABLE :: ipki, id_varin      ! jpbasin x nvar
@@ -63,6 +65,7 @@ PROGRAM cdfzonalsum
   CHARACTER(LEN=256)                            :: ctyp                ! variable type on C-grid
   CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_namesi           ! input variable names
   CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cv_nameso           ! output variable names
+  CHARACTER(LEN=80 ), DIMENSION(:), ALLOCATABLE :: cv_fix              ! name of the specified variable to process (-var option)
   CHARACTER(LEN=4  ), DIMENSION(5)              :: cbasin=(/'_glo','_atl','_inp','_ind','_pac'/) ! sub basin suffixes
 
   TYPE(variable), DIMENSION(:),     ALLOCATABLE :: stypvari            ! structure for input variables
@@ -70,21 +73,25 @@ PROGRAM cdfzonalsum
 
   LOGICAL                                       :: lpdep =.FALSE.      ! flag for depth sign (default dep < 0)
   LOGICAL                                       :: lpdeg =.FALSE.      ! flag for per degree normalization
+  LOGICAL                                       :: lvar  =.FALSE.      ! flag for specified variables processing
+  LOGICAL                                       :: ldebug   =.FALSE.   ! flag for activated debug print 
   LOGICAL                                       :: l2d   =.FALSE.      ! flag for 2D files
   LOGICAL                                       :: lchk  =.FALSE.      ! flag for missing files
+  LOGICAL, DIMENSION(:),            ALLOCATABLE :: lbad                ! flag array for variable selection
   !!----------------------------------------------------------------------
   CALL ReadCdfNames()
 
   narg= iargc()
   IF ( narg == 0 ) THEN
      PRINT *,' usage : cdfzonalsum IN-file point_type [ BASIN-file] ...'
-     PRINT *,'                  ... [-pdep | --positive_depths]'
-     PRINT *,'                  ... [-pdeg | --per_degree]'
+     PRINT *,'                  ... [-var var1,var2,..] [-pdep | --positive_depths]'
+     PRINT *,'                  ... [-pdeg | --per_degree] [-debug]'
      PRINT *,'      '
      PRINT *,'     PURPOSE :'
      PRINT *,'       Compute the zonal sum of all the variables available in the' 
      PRINT *,'       input file. This program assume that all the variables are'
      PRINT *,'       located on the same C-grid point, specified on the command line.'
+     PRINT *,'         Using -var option limits the variables to be processed.'
      PRINT *,'      '
      PRINT *,'       Zonal sum is in fact the integral value computed along the I coordinate.'
      PRINT *,'       The result is a vertical slice, in the meridional direction.'
@@ -100,6 +107,7 @@ PROGRAM cdfzonalsum
      PRINT *,'       [BASIN-file] : netcdf file describing sub basins, similar to '
      PRINT *,'                      ', TRIM(cn_fbasins),'. If this name is not given '
      PRINT *,'                      as option, only the global zonal integral is computed.'
+     PRINT *,'       [-var var1,var2,.. ] : Comma separated list of selected variables'
      PRINT *,'       [-pdep | --positive_depths ] : use positive depths in the output file.'
      PRINT *,'                      Default behaviour is to have negative depths.'
      PRINT *,'       [-pdeg | --per_degree ] : When using this option, the zonal integral'
@@ -107,6 +115,7 @@ PROGRAM cdfzonalsum
      PRINT *,'                      done with cdfzonalintdeg program, which is now merged'
      PRINT *,'                      in this one.'
      PRINT *,'                      Default behaviour is not to normalize.'
+     PRINT *,'       [-debug ] : add some print for debug'
      PRINT *,'      '
      PRINT *,'     REQUIRED FILES :'
      PRINT *,'       ',TRIM(cn_fhgr),', ', TRIM(cn_fzgr),' and ', TRIM(cn_fmsk)
@@ -127,8 +136,12 @@ PROGRAM cdfzonalsum
   DO WHILE ( ijarg <= narg ) 
     CALL getarg( ijarg, cldum ) ; ijarg=ijarg+1
     SELECT CASE (cldum)
-    CASE ( '-pdep' , '--positive_depths' ) ; lpdep =.TRUE.
-    CASE ( '-pdeg' , '--per_degree'      ) ; lpdeg =.TRUE.
+    CASE ( '-pdep' , '--positive_depths' ) ; lpdep  =.TRUE.
+    CASE ( '-pdeg' , '--per_degree'      ) ; lpdeg  =.TRUE.
+    CASE ( '-debug'                      ) ; ldebug =.TRUE.
+    CASE ( '-var'                        ) ; lvar   =.TRUE.
+                                             CALL getarg( ijarg, cldum) ; ijarg=ijarg+1
+                                             CALL ParseVars(cldum)
     CASE DEFAULT
       ireq=ireq+1
       SELECT CASE (ireq)
@@ -143,6 +156,14 @@ PROGRAM cdfzonalsum
     END SELECT
   END DO
 
+  IF ( ldebug ) THEN  ! additional print for debuging
+     PRINT *,' Option -pdep     ', lpdep
+     PRINT *,' Option -pdeg     ', lpdeg
+     PRINT *,' Option -debug    ', ldebug
+     PRINT *,' Option -var      ', lvar
+     PRINT *,' NPBASINS       = ', npbasins
+  ENDIF
+
   ! check  files existence
   lchk = lchk .OR. chkfile (cn_fhgr)
   lchk = lchk .OR. chkfile (cn_fzgr)
@@ -177,14 +198,35 @@ PROGRAM cdfzonalsum
   END SELECT
 
   nvarin  = getnvar(cf_in)   ! number of input variables
-  ALLOCATE ( cv_namesi(nvarin),          ipki(nvarin),          id_varin (nvarin)          )
-  ALLOCATE ( cv_nameso(npbasins*nvarin), ipko(npbasins*nvarin), id_varout(npbasins*nvarin) )
-  ALLOCATE ( stypvari(nvarin)                                                              )
-  ALLOCATE ( stypvaro(npbasins*nvarin)                                                     )
+  IF ( .NOT. lvar ) THEN
+    nvaro = nvarin
+  ENDIF
+
+  nvarmx = npbasins * nvaro
+  IF ( ldebug ) PRINT *,' NVARMX (output) :', nvarmx
+
+  ALLOCATE ( cv_namesi(nvarin), ipki(nvarin), id_varin (nvarin) )
+  ALLOCATE ( cv_nameso(nvarmx), ipko(nvarmx), id_varout(nvarmx) )
+  ALLOCATE ( stypvari(nvarin)                                   )
+  ALLOCATE ( stypvaro(nvarmx)                                   )
 
   cv_namesi(1:nvarin) = getvarname(cf_in, nvarin, stypvari )
   ipki     (1:nvarin) = getipk    (cf_in, nvarin           )
 
+  IF ( lvar )  THEN
+     ALLOCATE ( lbad(nvarin) )
+     lbad(:) = .true.  ! 
+     ! tricks : in case of specified variables, set ipki to 0 all variables
+     !          not choosen.
+     DO ji = 1, nvaro
+       DO jvar = 1, nvarin
+         IF ( cv_namesi(jvar) == cv_fix(ji) ) lbad(jvar) = .false.
+       END DO
+     END DO
+     WHERE ( lbad ) ipki=0
+     DEALLOCATE (lbad )
+  ENDIF
+
   ! buildt output filename
   nvar = 0  ! over all number of valid variables for zonal sum ( < nvarin)
   ivar = 0  ! over all variable counter ( nvar x basins)
@@ -238,7 +280,7 @@ PROGRAM cdfzonalsum
         END DO
      ENDIF
   END DO
-
+ 
   npiglo = getdim (cf_in, cn_x)
   npjglo = getdim (cf_in, cn_y)
   npk    = getdim (cf_in, cn_z)
@@ -340,5 +382,44 @@ PROGRAM cdfzonalsum
   END DO ! next variable
 
   ierr = closeout(ncout)
+CONTAINS
+   SUBROUTINE ParseVars (cdum)
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE ParseVars  ***
+      !!
+      !! ** Purpose :  Decode -var option from command line
+      !!
+      !! ** Method  :  look for , in the argument string and set the number of
+      !!         variable (nvaro), allocate cv_fix array and fill it with the
+      !!         decoded  names.
+      !!
+      !!----------------------------------------------------------------------
+      CHARACTER(LEN=*), INTENT(in) :: cdum
+
+      CHARACTER(LEN=80), DIMENSION(100) :: cl_dum  ! 100 is arbitrary
+      INTEGER  :: ji
+      INTEGER  :: inchar,  i1=1
+      !!----------------------------------------------------------------------
+
+      inchar= LEN(TRIM(cdum))
+      ! scan the input string and look for ',' as separator
+      DO ji=1,inchar
+         IF ( cdum(ji:ji) == ',' ) THEN
+            cl_dum(nvaro) = cdum(i1:ji-1)
+            i1=ji+1
+            nvaro=nvaro+1
+         ENDIF
+      ENDDO
+
+      ! last name of the list does not have a ','
+      cl_dum(nvaro) = cdum(i1:inchar)
+
+      ALLOCATE ( cv_fix(nvaro) )
+      IF ( ldebug) PRINT *,' SELECTED VARIABLES :'
+      DO ji=1, nvaro
+         cv_fix(ji) = cl_dum(ji)
+         IF ( ldebug) PRINT *, "    ",TRIM(cv_fix(ji))
+      ENDDO
+   END SUBROUTINE ParseVars
 
 END PROGRAM cdfzonalsum
diff --git a/cdfzoom.f90 b/src/cdfzoom.f90
similarity index 97%
rename from cdfzoom.f90
rename to src/cdfzoom.f90
index 9a704ca..daff5d0 100644
--- a/cdfzoom.f90
+++ b/src/cdfzoom.f90
@@ -152,7 +152,13 @@ PROGRAM cdfzoom
   IF ( ierr == 1 ) THEN 
      nt = getdim(cf_in, 'step', cldum, ierr)
      IF ( ierr == 1 ) THEN
-        PRINT *,' No time or step dim found ' 
+        nt = getdim(cf_in, 'time', cldum, ierr)
+        IF ( ierr == 1 ) THEN
+           nt = getdim(cf_in, 't', cldum, ierr)
+           IF ( ierr == 1 ) THEN
+             PRINT *,' No time or step dim found ' 
+           ENDIF
+        ENDIF
      ENDIF
   ENDIF
 
diff --git a/eos.f90 b/src/eos.f90
similarity index 76%
rename from eos.f90
rename to src/eos.f90
index b172e2d..4c9fd6b 100644
--- a/eos.f90
+++ b/src/eos.f90
@@ -19,8 +19,10 @@ MODULE eos
 
   PRIVATE
   PUBLIC :: sigma0
-  PUBLIC :: eosbn2
   PUBLIC :: sigmai
+  PUBLIC :: spice
+  PUBLIC :: sigmantr
+  PUBLIC :: eosbn2
   PUBLIC :: albet
   PUBLIC :: beta
 
@@ -81,8 +83,8 @@ CONTAINS
        END DO
     END DO
 
+    !$OMP PARALLEL DO SCHEDULE(RUNTIME)
     DO jj = 1, kpj
-       !
        DO ji = 1, kpi
 
           zt  = ptem (ji,jj)          ! interpolated T
@@ -102,9 +104,130 @@ CONTAINS
           sigma0(ji,jj) = ( zr4*zs + zr3*zsr + zr2 ) *zs + zr1 - zrau0
        END DO
     END DO
+    !$OMP END PARALLEL DO
 
   END FUNCTION sigma0
 
+  FUNCTION sigmantr( ptem, psal, kpi,kpj) 
+    !! --------------------------------------------------------------------
+    !! ** Purpose :   Compute the  neutral volumic mass (kg/m3) from known
+    !!      potential temperature and salinity fields using an equation of
+    !!      state. 
+    !!
+    !! ** Method  :
+    !!       McDougall and Jackett (2005) equation of state.
+    !!              potential temperature         t        deg celsius
+    !!              salinity                      s        psu
+    !!              neutral density               rho      kg/m**3
+    !!       result is not masked at this stage.
+    !!       Check value: rho(20,35) = 1024.59416751197 kg/m**3  -1000.
+    !!       t = 20 deg celcius, s=35 psu
+    !!
+    !! ** References : McDougall and Jackett, The material derivative of neutral density
+    !!        Journal of Marine Research, 63, 159-185, 2005
+    !! --------------------------------------------------------------------
+    REAL(KIND=4), DIMENSION(kpi,kpj), INTENT(in) :: ptem, psal ! temperature salinity
+    INTEGER(KIND=4),                  INTENT(in) :: kpi,kpj    ! dimension of 2D arrays
+    REAL(KIND=8), DIMENSION(kpi,kpj) :: sigmantr          ! return value
+
+    INTEGER(KIND=4)                   :: ji, jj
+    REAL(KIND=8), DIMENSION (kpi,kpj) :: dl_ws
+    REAL(KIND=8)                      :: dl_t, dl_s, dl_sr
+    REAL(KIND=8)                      :: dl_r1, dl_r2, dl_r3, dl_r4, dl_r5
+    !! --------------------------------------------------------------------
+    !$OMP PARALLEL DO SCHEDULE(RUNTIME)
+    DO jj = 1, kpj
+       DO ji = 1, kpi
+          dl_t = ptem(ji,jj)
+          dl_s = psal(ji,jj)
+          dl_sr= SQRT( ABS(dl_s) )
+       ! Numerator
+          ! T-Polynome
+          dl_r1= ( ( -4.3159255086706703d-4*dl_t+8.1157118782170051d-2 )*dl_t+2.2280832068441331d-1 )*dl_t+1002.3063688892480d0
+          ! S-T Polynome
+          dl_r2= ( -1.7052298331414675d-7*dl_s-3.1710675488863952d-3*dl_t-1.0304537539692924d-4 )*dl_s
+       ! Denominator
+          ! T-Polynome
+          dl_r3= ( ( (-2.3850178558212048d-9*dl_t -1.6212552470310961d-7 )*dl_t+7.8717799560577725d-5 )*dl_t+4.3907692647825900d-5 )*dl_t+     1.0d0
+          ! S-T Polynome
+          dl_r4= ( ( -2.2744455733317707d-9*dl_t*dl_t+6.0399864718597388d-6)*dl_t-5.1268124398160734d-4 )*dl_s
+          ! S-T Polynome
+          dl_r5= ( -1.3409379420216683d-9*dl_t*dl_t-3.6138532339703262d-5)*dl_s*dl_sr
+
+          ! Neutral density
+          sigmantr(ji,jj) = ( dl_r1 + dl_r2 ) / ( dl_r3 + dl_r4 + dl_r5 ) -1000.d0
+       ENDDO
+    ENDDO
+    !$OMP END PARALLEL DO
+
+
+  END FUNCTION sigmantr
+
+  FUNCTION spice ( ptem, psal, kpi, kpj )
+    !!---------------------------------------------------------------------
+    !!                  ***  FUNCTION spice  ***
+    !!
+    !! ** Purpose :  Compute spiciness from T S fields. 
+    !!
+    !! ** Method  :  spiciness = sum(i=0,5)[sum(j=0,4)[b(i,j)*theta^i*(s-35)^j]]
+    !!                   with:  b     -> coefficients
+    !!                          theta -> potential temperature
+    !!                          s     -> salinity
+    !!
+    !!  **  Example:
+    !!       spice(15,33)=   0.5445863      0.544586321373410  calcul en double
+    !!       spice(15,33)=   0.5445864      (calcul en simple precision) 
+    !!
+    !!  ** References : Flament (2002) "A state variable for characterizing
+    !!              water masses and their diffusive stability: spiciness."
+    !!              Progress in Oceanography Volume 54, 2002, Pages 493-501.
+    !!
+    !!----------------------------------------------------------------------
+    REAL(KIND=4), DIMENSION(kpi,kpj), INTENT(in) :: ptem, psal ! temperature salinity
+    INTEGER(KIND=4),                  INTENT(in) :: kpi,kpj    ! dimension of 2D arrays
+    REAL(KIND=8), DIMENSION(kpi,kpj)             :: spice      ! return value
+
+    INTEGER(KIND=4)                        :: ji,jj     ! dummy loop index
+    INTEGER(KIND=4)                        :: jig,jjg     ! dummy loop index
+    REAL(KIND=8), SAVE, DIMENSION(6,5)     :: dl_bet    ! coefficients of spiciness formula
+    REAL(KIND=8),       DIMENSION(kpi,kpj) :: dl_spi    ! spiciness
+    REAL(KIND=8),       DIMENSION(kpi,kpj) :: dl_salref ! reference salinity
+    REAL(KIND=8),       DIMENSION(kpi,kpj) :: dl_tempt  ! working array
+    REAL(KIND=8),       DIMENSION(kpi,kpj) :: dl_salt   ! working array
+
+    LOGICAL, SAVE                        :: lfrst=.TRUE.!
+    !!----------------------------------------------------------------------
+    IF ( lfrst ) THEN
+       lfrst = .false.
+       ! Define coefficients to compute spiciness (R*8)
+       dl_bet(1,:) = (/       0.d0,   7.7442d-01,    -5.85d-03,    -9.84d-04,    -2.06d-04/)
+       dl_bet(2,:) = (/ 5.1655d-02,    2.034d-03,   -2.742d-04,     -8.5d-06,     1.36d-05/)
+       dl_bet(3,:) = (/6.64783d-03,  -2.4681d-04,   -1.428d-05,    3.337d-05,    7.894d-06/)
+       dl_bet(4,:) = (/-5.4023d-05,    7.326d-06,   7.0036d-06,  -3.0412d-06,  -1.0853d-06/)
+       dl_bet(5,:) = (/  3.949d-07,   -3.029d-08,  -3.8209d-07,   1.0012d-07,   4.7133d-08/)
+       dl_bet(6,:) = (/  -6.36d-10,   -1.309d-09,    6.048d-09,  -1.1409d-09,   -6.676d-10/)
+    ENDIF
+    ! spiciness 
+    dl_spi(:,:)    = 0.d0
+    dl_salref(:,:) = psal(:,:) - 35.d0
+    dl_tempt(:,:)  = 1.d0
+!$OMP PARALLEL DO SCHEDULE(RUNTIME)
+    DO jjg=1, kpj
+    DO ji=1,6
+       dl_salt(:,jjg) = 1.d0
+       DO jj=1,5
+           dl_spi( :,jjg) = dl_spi (:,jjg) +   dl_bet (ji,jj) * dl_tempt(:,jjg) * dl_salt(:,jjg)
+           dl_salt(:,jjg) = dl_salt(:,jjg) * dl_salref( :,jjg )
+       END DO
+       dl_tempt(:,jjg) = dl_tempt(:,jjg) * ptem(:,jjg)
+    END DO
+    END DO
+!$OMP END PARALLEL DO
+
+    spice(:,:) = dl_spi( :,:)
+
+  END FUNCTION spice
+
   FUNCTION sigmai_dep ( ptem, psal, pref, kpi,kpj)
     !! --------------------------------------------------------------------
     !! ** Purpose :   Compute the  density referenced to pref (ratio rho/rau0) 
@@ -140,7 +263,7 @@ CONTAINS
     REAL(KIND=8) :: dlt, dls      
     REAL(KIND=8) :: dla, dla1, dlaw, dlb, dlb1, dlbw, dlc, dle, dlk0, dlkw 
     REAL(kind=8) :: dlrhop, dlr1, dlr2, dlr3, dlref
-
+    !! --------------------------------------------------------------------
     dlref      = pref
     sigmai_dep = 0.d0
     DO jj = 1, kpj
@@ -149,6 +272,7 @@ CONTAINS
        END DO
     END DO
 
+    !$OMP PARALLEL DO SCHEDULE(RUNTIME)
     DO jj=1,kpj
        DO ji=1,kpi
 
@@ -213,6 +337,7 @@ CONTAINS
 
        ENDDO
     ENDDO
+    !$OMP END PARALLEL DO
 
   END FUNCTION sigmai_dep
 
@@ -259,6 +384,7 @@ CONTAINS
        END DO
     END DO
 
+    !$OMP PARALLEL DO SCHEDULE(RUNTIME)
     DO jj=1,kpj
        DO ji=1,kpi
 
@@ -324,6 +450,7 @@ CONTAINS
 
        ENDDO
     ENDDO
+    !$OMP END PARALLEL DO
 
   END FUNCTION sigmai_dep2d
 
@@ -354,6 +481,7 @@ CONTAINS
     !!----------------------------------------------------------------------
 
     zh = pdep
+    !$OMP PARALLEL DO SCHEDULE(RUNTIME)
     DO jj = 1, kpj
        DO ji = 1, kpi
           zgde3w = zgrav / pe3w(ji,jj)
@@ -390,6 +518,7 @@ CONTAINS
                &                     - ( psal(ji,jj,kup) - psal(ji,jj,kdown) ) )
        END DO
     END DO
+    !$OMP END PARALLEL DO
 
   END FUNCTION eosbn2
 
@@ -413,8 +542,9 @@ CONTAINS
     REAL(KIND=8)    :: zt, zs, zh  ! working local variables
     !!----------------------------------------------------------------------
     zh = pdep
-    DO ji=1,kpi
-       DO jj=1,kpj
+    !$OMP PARALLEL DO SCHEDULE(RUNTIME)
+     DO jj=1,kpj
+       DO ji=1,kpi
           zt =  ptem(ji,jj)         ! potential temperature
           zs =  psal(ji,jj)- 35.0   ! salinity anomaly (s-35)
 
@@ -432,6 +562,7 @@ CONTAINS
                &                               + 0.380374e-04 ) * zh
        END DO
     END DO
+    !$OMP END PARALLEL DO
 
   END FUNCTION albet
 
@@ -454,8 +585,9 @@ CONTAINS
     REAL(KIND=8)    :: zt, zs, zh  ! working variables
     !!----------------------------------------------------------------------
     zh = pdep
-    DO ji=1,kpi
-       DO jj=1,kpj
+    !$OMP PARALLEL DO SCHEDULE(RUNTIME)
+    DO jj=1,kpj
+       DO ji=1,kpi
           zt =  ptem(ji,jj)         ! potential temperature
           zs =  psal(ji,jj)- 35.0   ! salinity anomaly (s-35)
 
@@ -472,6 +604,7 @@ CONTAINS
                &                             - 0.121555e-07 ) * zh
        END DO
     END DO
+    !$OMP END PARALLEL DO
 
   END FUNCTION beta
 
diff --git a/modcdfnames.f90 b/src/modcdfnames.f90
similarity index 50%
rename from modcdfnames.f90
rename to src/modcdfnames.f90
index 4dcb86f..e7aec40 100644
--- a/modcdfnames.f90
+++ b/src/modcdfnames.f90
@@ -12,113 +12,132 @@ MODULE modCdfNames
   PUBLIC
 
   ! Dimension name : cn_. [ 1 letter only ]
-  CHARACTER(LEN=20) :: cn_x='x'               !: longitude, I dimension
-  CHARACTER(LEN=20) :: cn_y='y'               !: latitude,  J dimension
-  CHARACTER(LEN=20) :: cn_z='depth'           !: depth, z dimension
-  CHARACTER(LEN=20) :: cn_t='time_counter'    !: time dimension
+  CHARACTER(LEN=256) :: cn_x='x'               !: longitude, I dimension
+  CHARACTER(LEN=256) :: cn_y='y'               !: latitude,  J dimension
+  CHARACTER(LEN=256) :: cn_z='depth'           !: depth, z dimension
+  CHARACTER(LEN=256) :: cn_t='time_counter'    !: time dimension
 
   ! Dimension variable
-  CHARACTER(LEN=20) :: cn_vlon2d  = 'nav_lon'      !: longitude
-  CHARACTER(LEN=20) :: cn_vlat2d  = 'nav_lat'      !: latitude
-  CHARACTER(LEN=20) :: cn_vdeptht = 'deptht'       !: depth
-  CHARACTER(LEN=20) :: cn_vdepthu = 'depthu'       !: depth
-  CHARACTER(LEN=20) :: cn_vdepthv = 'depthv'       !: depth
-  CHARACTER(LEN=20) :: cn_vdepthw = 'depthw'       !: depth
-  CHARACTER(LEN=20) :: cn_vtimec  = 'time_counter' !: time 
+  CHARACTER(LEN=256) :: cn_vlon2d  = 'nav_lon'      !: longitude
+  CHARACTER(LEN=256) :: cn_vlat2d  = 'nav_lat'      !: latitude
+  CHARACTER(LEN=256) :: cn_vdeptht = 'deptht'       !: depth
+  CHARACTER(LEN=256) :: cn_vdepthu = 'depthu'       !: depth
+  CHARACTER(LEN=256) :: cn_vdepthv = 'depthv'       !: depth
+  CHARACTER(LEN=256) :: cn_vdepthw = 'depthw'       !: depth
+  CHARACTER(LEN=256) :: cn_vtimec  = 'time_counter' !: time 
+  CHARACTER(LEN=256) :: cn_vlon1d  = 'lon'          !: longitude 1d
+  CHARACTER(LEN=256) :: cn_vlat1d  = 'lat'          !: latitude  1d
 
   ! Attribute of a variable
-  CHARACTER(LEN=20) :: cn_missing_value = '_FillValue' !: missing value (to be replaced bby _Fill_Value)
+  CHARACTER(LEN=256) :: cn_missing_value = '_FillValue' !: missing value (to be replaced bby _Fill_Value)
 
   ! Metrics
-  CHARACTER(LEN=20) :: cn_ve1t='e1t', cn_ve2t='e2t'   !: e.t
-  CHARACTER(LEN=20) :: cn_ve1u='e1u', cn_ve2u='e2u'   !: e.u
-  CHARACTER(LEN=20) :: cn_ve1v='e1v', cn_ve2v='e2v'   !: e.v
-  CHARACTER(LEN=20) :: cn_ve1f='e1f', cn_ve2f='e2f'   !: e.v
-  CHARACTER(LEN=20) :: cn_ve3t='e3t', cn_ve3w='e3w'   !: e3.
-  CHARACTER(LEN=20) :: cn_vff='ff'
+  CHARACTER(LEN=256) :: cn_ve1t='e1t', cn_ve2t='e2t'   !: e.t
+  CHARACTER(LEN=256) :: cn_ve1u='e1u', cn_ve2u='e2u'   !: e.u
+  CHARACTER(LEN=256) :: cn_ve1v='e1v', cn_ve2v='e2v'   !: e.v
+  CHARACTER(LEN=256) :: cn_ve1f='e1f', cn_ve2f='e2f'   !: e.v
+  CHARACTER(LEN=256) :: cn_ve3t='e3t', cn_ve3w='e3w'   !: e3.
+  CHARACTER(LEN=256) :: cn_vff='ff'
 
-  CHARACTER(LEN=20) :: cn_gdept='gdept', cn_gdepw='gdepw'   !: 1d dep variable
-  CHARACTER(LEN=20) :: cn_hdept='hdept', cn_hdepw='hdepw'   !: 2d dep variable
+  CHARACTER(LEN=256) :: cn_gdept='gdept', cn_gdepw='gdepw'   !: 1d dep variable
+  CHARACTER(LEN=256) :: cn_hdept='hdept', cn_hdepw='hdepw'   !: 2d dep variable
 
-  CHARACTER(LEN=20) :: cn_glamt='glamt', cn_gphit='gphit'   !:  glam gphi
-  CHARACTER(LEN=20) :: cn_glamu='glamu', cn_gphiu='gphiu'   !:  glam gphi
-  CHARACTER(LEN=20) :: cn_glamv='glamv', cn_gphiv='gphiv'   !:  glam gphi
-  CHARACTER(LEN=20) :: cn_glamf='glamf', cn_gphif='gphif'   !:  glam gphi
+  CHARACTER(LEN=256) :: cn_glamt='glamt', cn_gphit='gphit'   !:  glam gphi
+  CHARACTER(LEN=256) :: cn_glamu='glamu', cn_gphiu='gphiu'   !:  glam gphi
+  CHARACTER(LEN=256) :: cn_glamv='glamv', cn_gphiv='gphiv'   !:  glam gphi
+  CHARACTER(LEN=256) :: cn_glamf='glamf', cn_gphif='gphif'   !:  glam gphi
+
+  ! Mask variables
+  CHARACTER(LEN=256) :: cn_tmask='tmask', cn_umask='umask'   !:  tmask, umask
+  CHARACTER(LEN=256) :: cn_vmask='vmask', cn_fmask='fmask'   !:  tmask, umask
 
   ! Generic mesh-mask file names  cn_f...
-  CHARACTER(LEN=20) :: cn_fzgr='mesh_zgr.nc'
-  CHARACTER(LEN=20) :: cn_fhgr='mesh_hgr.nc'
-  CHARACTER(LEN=20) :: cn_fmsk='mask.nc'
-  CHARACTER(LEN=20) :: cn_fcoo='coordinates.nc'
-  CHARACTER(LEN=20) :: cn_fbasins='new_maskglo.nc'
+  CHARACTER(LEN=256) :: cn_fzgr='mesh_zgr.nc'
+  CHARACTER(LEN=256) :: cn_fhgr='mesh_hgr.nc'
+  CHARACTER(LEN=256) :: cn_fmsk='mask.nc'
+  CHARACTER(LEN=256) :: cn_fcoo='coordinates.nc'
+  CHARACTER(LEN=256) :: cn_fbasins='new_maskglo.nc'
 
   ! Variable name  : cn_v... [ starts with cn_v ]
-  CHARACTER(LEN=20) :: cn_votemper='votemper' !: temperature
-  CHARACTER(LEN=20) :: cn_vosaline='vosaline' !: salinity
-  CHARACTER(LEN=20) :: cn_vozocrtx='vozocrtx' !: zonal velocity
-  CHARACTER(LEN=20) :: cn_vomecrty='vomecrty' !: meridional velocity
-  CHARACTER(LEN=20) :: cn_vomeeivv='vomeeivv' !: meridional Eddy Induced Velocity
-  CHARACTER(LEN=20) :: cn_vovecrtz='vovecrtz' !: vertical velocity
-  CHARACTER(LEN=20) :: cn_sossheig='sossheig' !: Sea Surface Height
-  CHARACTER(LEN=20) :: cn_somxl010='somxl010' !: Mixed layer depth (density criterium)
-  CHARACTER(LEN=20) :: cn_somxlt02='somxlt02' !: Mixed layer depth (temperature criterium)
-  CHARACTER(LEN=20) :: cn_sozotaux='sozotaux' !: Zonal wind stress
-
-  CHARACTER(LEN=20) :: cn_sohefldo='sohefldo' !: Total Heat FLux
-  CHARACTER(LEN=20) :: cn_solhflup='solhflup' !: Latent Heat FLux 
-  CHARACTER(LEN=20) :: cn_sosbhfup='sosbhfup' !: Sensible heat Flux
-  CHARACTER(LEN=20) :: cn_solwfldo='solwfldo' !: Long Wave downward Heat Flux
-  CHARACTER(LEN=20) :: cn_soshfldo='soshfldo' !: Solar Heat FLux
-
-  CHARACTER(LEN=20) :: cn_sowaflup='sowaflup' !: Fresh Water Flux
-  CHARACTER(LEN=20) :: cn_sowaflcd='sowaflcd' !: Concentration Dilution water flux
-  CHARACTER(LEN=20) :: cn_sowafldp='sowafldp' !: SSS damping water Flux
-  CHARACTER(LEN=20) :: cn_iowaflup='iowaflup' !: Ice Ocean Water flux ( + = freezing, - = melting)
-  CHARACTER(LEN=20) :: cn_soicecov='soicecov' !: Ice cover
+  CHARACTER(LEN=256) :: cn_votemper='votemper' !: temperature
+  CHARACTER(LEN=256) :: cn_vosaline='vosaline' !: salinity
+  CHARACTER(LEN=256) :: cn_vozocrtx='vozocrtx' !: zonal velocity
+  CHARACTER(LEN=256) :: cn_vomecrty='vomecrty' !: meridional velocity
+  CHARACTER(LEN=256) :: cn_vomeeivv='vomeeivv' !: meridional Eddy Induced Velocity
+  CHARACTER(LEN=256) :: cn_vovecrtz='vovecrtz' !: vertical velocity
+  CHARACTER(LEN=256) :: cn_sossheig='sossheig' !: Sea Surface Height
+  CHARACTER(LEN=256) :: cn_somxl010='somxl010' !: Mixed layer depth (density criterium)
+  CHARACTER(LEN=256) :: cn_somxlt02='somxlt02' !: Mixed layer depth (temperature criterium)
+  CHARACTER(LEN=256) :: cn_sozotaux='sozotaux' !: Zonal wind stress
+
+  CHARACTER(LEN=256) :: cn_sohefldo='sohefldo' !: Total Heat FLux
+  CHARACTER(LEN=256) :: cn_solhflup='solhflup' !: Latent Heat FLux 
+  CHARACTER(LEN=256) :: cn_sosbhfup='sosbhfup' !: Sensible heat Flux
+  CHARACTER(LEN=256) :: cn_solwfldo='solwfldo' !: Long Wave downward Heat Flux
+  CHARACTER(LEN=256) :: cn_soshfldo='soshfldo' !: Solar Heat FLux
+
+  CHARACTER(LEN=256) :: cn_sowaflup='sowaflup' !: Fresh Water Flux
+  CHARACTER(LEN=256) :: cn_sowaflcd='sowaflcd' !: Concentration Dilution water flux
+  CHARACTER(LEN=256) :: cn_sowafldp='sowafldp' !: SSS damping water Flux
+  CHARACTER(LEN=256) :: cn_iowaflup='iowaflup' !: Ice Ocean Water flux ( + = freezing, - = melting)
+  CHARACTER(LEN=256) :: cn_soicecov='soicecov' !: Ice cover
+
+  CHARACTER(LEN=256) :: cn_iicbmass='berg_mass'!: Mass of Icebergs (kg/m2)
+  CHARACTER(LEN=256) :: cn_iicbmelt='berg_melt'!: Melting rate of icebergs (kg/m2/s)
 
   ! MOC variables
-  CHARACTER(LEN=20) :: cn_zomsfatl='zomsfatl' !: moc in the Atlantic
-  CHARACTER(LEN=20) :: cn_zomsfglo='zomsfglo' !: moc in the Global ocean
-  CHARACTER(LEN=20) :: cn_zomsfpac='zomsfpac' !: moc in the Pacific
-  CHARACTER(LEN=20) :: cn_zomsfinp='zomsfinp' !: moc in the Indo-Pacific
-  CHARACTER(LEN=20) :: cn_zomsfind='zomsfind' !: moc in the Indian ocean
-  CHARACTER(LEN=20) :: cn_zomsfinp0='zomsfinp0' !: moc in the Indo-Pacific Net
+  CHARACTER(LEN=256) :: cn_zomsfatl='zomsfatl' !: moc in the Atlantic
+  CHARACTER(LEN=256) :: cn_zomsfglo='zomsfglo' !: moc in the Global ocean
+  CHARACTER(LEN=256) :: cn_zomsfpac='zomsfpac' !: moc in the Pacific
+  CHARACTER(LEN=256) :: cn_zomsfinp='zomsfinp' !: moc in the Indo-Pacific
+  CHARACTER(LEN=256) :: cn_zomsfind='zomsfind' !: moc in the Indian ocean
+  CHARACTER(LEN=256) :: cn_zomsfinp0='zomsfinp0' !: moc in the Indo-Pacific Net
+  !
+  CHARACTER(LEN=256) :: cn_zoisoatl='zoisoatl' !: moc in the Atlantic
+  CHARACTER(LEN=256) :: cn_zoisoglo='zoisoglo' !: moc in the Global ocean
+  CHARACTER(LEN=256) :: cn_zoisopac='zoisopac' !: moc in the Pacific
+  CHARACTER(LEN=256) :: cn_zoisoinp='zoisoinp' !: moc in the Indo-Pacific
+  CHARACTER(LEN=256) :: cn_zoisoind='zoisoind' !: moc in the Indian ocean
+  CHARACTER(LEN=256) :: cn_zoisoinp0='zoisoinp0' !: moc in the Indo-Pacific Net
   
   ! transport variables
-  CHARACTER(LEN=20) :: cn_vozout='vozout'     !: product U x T at U point
-  CHARACTER(LEN=20) :: cn_vomevt='vomevt'     !: product V x T at V point
-  CHARACTER(LEN=20) :: cn_vozous='vozous'     !: product U x S at U point
-  CHARACTER(LEN=20) :: cn_vomevs='vomevs'     !: product V x S at V point
-  CHARACTER(LEN=20) :: cn_sozout='sozout'     !: product U x T at U point
-  CHARACTER(LEN=20) :: cn_somevt='somevt'     !: product V x T at V point
-  CHARACTER(LEN=20) :: cn_sozous='sozous'     !: product U x S at U point
-  CHARACTER(LEN=20) :: cn_somevs='somevs'     !: product V x S at V point
-  CHARACTER(LEN=20) :: cn_sozoutrp='sozoutrp' !: vertically integrated trp at U point
-  CHARACTER(LEN=20) :: cn_somevtrp='somevtrp' !: vertically integrated trp at V point
+  CHARACTER(LEN=256) :: cn_vozout='vozout'     !: product U x T at U point
+  CHARACTER(LEN=256) :: cn_vomevt='vomevt'     !: product V x T at V point
+  CHARACTER(LEN=256) :: cn_vozous='vozous'     !: product U x S at U point
+  CHARACTER(LEN=256) :: cn_vomevs='vomevs'     !: product V x S at V point
+  CHARACTER(LEN=256) :: cn_sozout='sozout'     !: product U x T at U point
+  CHARACTER(LEN=256) :: cn_somevt='somevt'     !: product V x T at V point
+  CHARACTER(LEN=256) :: cn_sozous='sozous'     !: product U x S at U point
+  CHARACTER(LEN=256) :: cn_somevs='somevs'     !: product V x S at V point
+  CHARACTER(LEN=256) :: cn_sozoutrp='sozoutrp' !: vertically integrated trp at U point
+  CHARACTER(LEN=256) :: cn_somevtrp='somevtrp' !: vertically integrated trp at V point
+  CHARACTER(LEN=256) :: cn_vouv='vouv'         !: product U x V at T point
 
   ! density, isopycnal diagnostics
-  CHARACTER(LEN=20) :: cn_vosigma0='vosigma0' !: potential density refered to surface
-  CHARACTER(LEN=20) :: cn_vosigmai='vosigmai' !: potential density refered to a partiular depth
-  CHARACTER(LEN=20) :: cn_vodepiso='vodepiso' !: depth of isopycnal
-  CHARACTER(LEN=20) :: cn_isothick='isothick' !: isopycnal tickness (from cdfsigintegr)
+  CHARACTER(LEN=256) :: cn_vosigma0='vosigma0' !: potential density refered to surface
+  CHARACTER(LEN=256) :: cn_vosigmai='vosigmai' !: potential density refered to a partiular depth
+  CHARACTER(LEN=256) :: cn_vosigntr='vosigntr' !: neutral density
+  CHARACTER(LEN=256) :: cn_vodepiso='vodepiso' !: depth of isopycnal
+  CHARACTER(LEN=256) :: cn_isothick='isothick' !: isopycnal tickness (from cdfsigintegr)
 
   ! Passive tracer variable
-  CHARACTER(LEN=20) :: cn_invcfc='invcfc'     !: CFC inventory
-  CHARACTER(LEN=20) :: cn_cfc11='cfc11'       !: CFC concentration
-  CHARACTER(LEN=20) :: cn_pendep='pendep'     !: CFC penetration depth (from cdfpendep)
+  CHARACTER(LEN=256) :: cn_invcfc='INVCFC'     !: CFC inventory
+  CHARACTER(LEN=256) :: cn_cfc11='CFC11'       !: CFC concentration
+  CHARACTER(LEN=256) :: cn_pendep='pendep'     !: CFC penetration depth (from cdfpendep)
   
   ! ice variable names
-  CHARACTER(LEN=20) :: cn_iicethic='iicethic' !: ice thickness
-  CHARACTER(LEN=20) :: cn_ileadfra='ileadfra' !: ice concentration
-  CHARACTER(LEN=20) :: cn_iicethic3='iicethic'!: ice thickness (LIM3)
-  CHARACTER(LEN=20) :: cn_ileadfra3='iiceconc'!: ice concentration (LIM3)
+  CHARACTER(LEN=256) :: cn_iicethic='iicethic' !: ice thickness
+  CHARACTER(LEN=256) :: cn_ileadfra='ileadfra' !: ice concentration
+  CHARACTER(LEN=256) :: cn_iicethic3='iicethic'!: ice thickness (LIM3)
+  CHARACTER(LEN=256) :: cn_ileadfra3='iiceconc'!: ice concentration (LIM3)
   
   ! Bathymetry
-  CHARACTER(LEN=20) :: cn_fbathymet='bathy_meter.nc' !: file Bathymetry in meters
-  CHARACTER(LEN=20) :: cn_fbathylev='bathy_level.nc' !: file Bathymetry in levels
+  CHARACTER(LEN=256) :: cn_fbathymet='bathy_meter.nc' !: file Bathymetry in meters
+  CHARACTER(LEN=256) :: cn_fbathylev='bathy_level.nc' !: file Bathymetry in levels
 
-  CHARACTER(LEN=20) :: cn_bathymet='Bathymetry' !: variable Bathymetry in meters
-  CHARACTER(LEN=20) :: cn_bathylev='bathy_level'!: variable Bathymetry in levels
+  CHARACTER(LEN=256) :: cn_bathymet='Bathymetry' !: variable Bathymetry in meters
+  CHARACTER(LEN=256) :: cn_bathylev='bathy_level'!: variable Bathymetry in levels
+  CHARACTER(LEN=256) :: cn_mbathy  ='mbathy'     !: variable mbathy in levels
 
   ! variables to be squared when performing cdfmoy
   INTEGER(KIND=4), PARAMETER :: jp_sqdvarmax=10
@@ -161,6 +180,8 @@ MODULE modCdfNames
     NAMELIST/nammetrics/ cn_vff
     NAMELIST/nammetrics/ cn_glamt, cn_glamu, cn_glamv, cn_glamf
     NAMELIST/nammetrics/ cn_gphit, cn_gphiu, cn_gphiv, cn_gphif
+    ! mask variables
+    NAMELIST/nammask/ cn_tmask, cn_umask, cn_vmask, cn_fmask
     !        mesh_zgr
     NAMELIST/nammetrics/ cn_gdept, cn_gdepw
     NAMELIST/nammetrics/ cn_hdept, cn_hdepw
@@ -173,11 +194,12 @@ MODULE modCdfNames
     NAMELIST/namvars/ cn_solwfldo, cn_soshfldo
     NAMELIST/namvars/ cn_sowaflup, cn_sowaflcd, cn_sowafldp, cn_iowaflup
     NAMELIST/namvars/ cn_zomsfatl, cn_zomsfglo, cn_zomsfpac, cn_zomsfinp, cn_zomsfind
+    NAMELIST/namvars/ cn_zoisoatl, cn_zoisoglo, cn_zoisopac, cn_zoisoinp, cn_zoisoind
     NAMELIST/namvars/ cn_vozout, cn_vomevt, cn_vozous, cn_vomevs
     NAMELIST/namvars/ cn_sozout, cn_somevt, cn_sozous, cn_somevs
     NAMELIST/namvars/ cn_sozoutrp, cn_somevtrp
     NAMELIST/namvars/ cn_soicecov
-    NAMELIST/namvars/ cn_vosigma0, cn_vosigmai, cn_vodepiso, cn_isothick
+    NAMELIST/namvars/ cn_vosigma0, cn_vosigmai, cn_vosigntr, cn_vodepiso, cn_isothick
     NAMELIST/namvars/ cn_iicethic, cn_ileadfra
     NAMELIST/namvars/ cn_invcfc,   cn_cfc11,    cn_pendep
 
@@ -191,7 +213,7 @@ MODULE modCdfNames
     NAMELIST/nammeshmask/ cn_fzgr, cn_fhgr, cn_fmsk, cn_fcoo, cn_fbasins
 
     ! Bathymetry
-    NAMELIST/nambathy/ cn_fbathymet, cn_fbathylev, cn_bathymet, cn_bathylev
+    NAMELIST/nambathy/ cn_fbathymet, cn_fbathylev, cn_bathymet, cn_bathylev, cn_mbathy
   !!----------------------------------------------------------------------
   !! CDFTOOLS_3.0 , MEOM 2011
   !! $Id$
@@ -216,11 +238,11 @@ CONTAINS
     !!               variable NAM_CDF_NAMES
     !!
     !!----------------------------------------------------------------------
-    CHARACTER(LEN=90) :: cl_namlist= 'nam_cdf_names'
-    CHARACTER(LEN=20) :: cl_env    = 'NAM_CDF_NAMES'
-    CHARACTER(LEN=90) :: cldum, cl_home
-    LOGICAL           :: ll_exist
-    INTEGER(KIND=4)   :: inam = 10
+    CHARACTER(LEN=90)  :: cl_namlist= 'nam_cdf_names'
+    CHARACTER(LEN=256) :: cl_env    = 'NAM_CDF_NAMES'
+    CHARACTER(LEN=90)  :: cldum, cl_home
+    LOGICAL            :: ll_exist
+    INTEGER(KIND=4)    :: inam = 10
     !!----------------------------------------------------------------------
     CALL getenv ('HOME', cl_home) 
 
diff --git a/modpoly.f90 b/src/modpoly.f90
similarity index 100%
rename from modpoly.f90
rename to src/modpoly.f90
diff --git a/modutils.f90 b/src/modutils.f90
similarity index 56%
rename from modutils.f90
rename to src/modutils.f90
index 35c8dd9..fdf84b8 100644
--- a/modutils.f90
+++ b/src/modutils.f90
@@ -25,7 +25,10 @@ MODULE modutils
   PRIVATE
   PUBLIC SetGlobalAtt
   PUBLIC SetFileName
+  PUBLIC GetList
   PUBLIC shapiro_fill_smooth
+  PUBLIC FillPool2D
+  PUBLIC FillPool3D
 
 CONTAINS
   SUBROUTINE SetGlobalAtt(cdglobal, cd_append)
@@ -99,6 +102,57 @@ CONTAINS
     ENDIF
   END FUNCTION SetFileName
 
+  SUBROUTINE GetList ( cd_list, klist, ksiz )
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE getlist  ***
+    !!
+    !! ** Purpose :   Expand list described with input string like
+    !!                k1,k2,k3  or k1-k2,k3 or any valid combination
+    !!
+    !! ** Method  :   Look for ',' and '-' in cd_list and interprets
+    !!
+    !!----------------------------------------------------------------------
+    CHARACTER(LEN=*),                           INTENT(in ) :: cd_list ! list to decipher
+    INTEGER(KIND=4), DIMENSION(:), ALLOCATABLE, INTENT(out) :: klist   ! deciphered integer list
+    INTEGER(KIND=4),                            INTENT(out) :: ksiz    ! size of the list
+
+    INTEGER(KIND=4),             PARAMETER :: jp_maxlist=500
+    INTEGER(KIND=4)                        :: ji, jk
+    INTEGER(KIND=4)                        :: inlev, ipos, iposm,  ik1, ik2
+    INTEGER(KIND=4), DIMENSION(jp_maxlist) :: itmp
+    CHARACTER(LEN=80)                      :: cldum
+    CHARACTER(LEN=80)                      :: cldum2
+    !----------------------------------------------------------------------------
+    cldum=cd_list
+    ipos=1
+    ksiz=0
+    DO WHILE (ipos /= 0 )
+       ipos=INDEX(cldum,',')
+       IF (ipos == 0 ) THEN
+          cldum2=cldum
+       ELSE
+          cldum2=cldum(1:ipos-1)
+       ENDIF
+
+       iposm=INDEX(cldum2,'-')
+       IF ( iposm == 0 ) THEN
+          ksiz=ksiz+1 ; IF (ksiz > jp_maxlist) STOP 'jp_maxlist too small in getlist '
+          READ(cldum2,* ) itmp(ksiz)
+       ELSE
+          READ(cldum2(1:iposm-1),*) ik1
+          READ(cldum2(iposm+1:),* ) ik2
+          DO jk = ik1,ik2
+             ksiz=ksiz+1 ; IF (ksiz > jp_maxlist) STOP 'jp_maxlist too small in getlist '
+             itmp(ksiz)=jk
+          ENDDO
+       ENDIF
+       cldum=cldum(ipos+1:)
+    ENDDO
+    ALLOCATE (klist(ksiz) )
+    klist(:)=itmp(1:ksiz)
+
+  END SUBROUTINE GetList
+
   SUBROUTINE shapiro_fill_smooth ( psig, kpi, kpj, kpass, cdfs, pbad, klmasktrue, psigf )
     !!---------------------------------------------------------------------
     !!                  ***  ROUTINE shapiro_fill_smooth  ***
@@ -247,4 +301,159 @@ CONTAINS
 
   END SUBROUTINE shapiro_fill_smooth
 
+  SUBROUTINE FillPool2D(kiseed, kjseed, kdta, kifill)
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE FillPool2D  ***
+    !!  
+    !! ** Purpose :  Replace all area surrounding by mask value by mask value
+    !!  
+    !! ** Method  :  flood fill algorithm
+    !!  
+    !!----------------------------------------------------------------------
+    INTEGER(KIND=4),                 INTENT(in)    :: kiseed, kjseed
+    INTEGER(KIND=4),                 INTENT(in)    :: kifill         ! pool value
+    INTEGER(KIND=2), DIMENSION(:,:), INTENT(inout) :: kdta           ! mask
+
+    INTEGER :: ik                       ! number of point change
+    INTEGER :: ip                       ! size of the pile
+    INTEGER :: ji, jj                   ! loop index
+    INTEGER :: iip1, iim1, ii, ij       ! working integer
+    INTEGER :: ipiglo, ipjglo           ! size of the domain, infered from kdta size
+
+    INTEGER(KIND=2), DIMENSION(:,:), ALLOCATABLE :: ipile    ! pile variable
+    INTEGER(KIND=2), DIMENSION(:,:), ALLOCATABLE :: idata   ! new bathymetry
+    !!----------------------------------------------------------------------
+    ! infer domain size from input array
+    ipiglo = SIZE(kdta,1)
+    ipjglo = SIZE(kdta,2)
+
+    ! allocate variable
+    ALLOCATE(ipile(2*ipiglo*ipjglo,2))
+    ALLOCATE(idata(ipiglo,ipjglo))
+
+    ! initialise variables
+    idata=kdta
+    ipile(:,:)=0
+    ipile(1,:)=[kiseed,kjseed]
+    ip=1; ik=0
+
+    ! loop until the pile size is 0 or if the pool is larger than the critical size
+    DO WHILE ( ip /= 0 ) ! .AND. ik < 600000);
+       ik=ik+1
+       ii=ipile(ip,1); ij=ipile(ip,2)
+       IF ( MOD(ik, 10000) == 0 ) PRINT *, 'IP =', ip, ik, ii,ij
+
+       ! update bathy and update pile size
+       idata(ii,ij) =kifill
+       ipile(ip,:)  =[0,0]; ip=ip-1
+
+       ! check neighbour cells and update pile ( assume E-W periodicity )
+       iip1=ii+1; IF ( iip1 == ipiglo+1 ) iip1=2
+       iim1=ii-1; IF ( iim1 == 0        ) iim1=ipiglo-1
+
+       IF (idata(ii, ij+1) > 0 ) THEN
+          ip=ip+1; ipile(ip,:)=[ii  ,ij+1]
+       END IF
+       IF (idata(ii, ij-1) > 0 ) THEN
+          ip=ip+1; ipile(ip,:)=[ii  ,ij-1]
+       END IF
+       IF (idata(iip1, ij) > 0 ) THEN
+          ip=ip+1; ipile(ip,:)=[iip1,ij  ]
+       END IF
+       IF (idata(iim1, ij) > 0 ) THEN
+          ip=ip+1; ipile(ip,:)=[iim1,ij  ]
+       END IF
+
+    END DO
+    kdta=idata;
+
+    DEALLOCATE(ipile); DEALLOCATE(idata)
+
+  END SUBROUTINE FillPool2D
+
+
+  SUBROUTINE FillPool3D(kiseed, kjseed, kkseed, kdta, kifill)
+    !!---------------------------------------------------------------------
+    !!                  ***  ROUTINE FillPool3D  ***
+    !!
+    !! ** Purpose :  Replace all area surrounding by mask value by mask value
+    !!
+    !! ** Method  :  flood fill algorithm
+    !!
+    !!----------------------------------------------------------------------
+    INTEGER(KIND=4),                   INTENT(in)    :: kiseed, kjseed, kkseed
+    INTEGER(KIND=4),                   INTENT(in)    :: kifill   ! new bathymetry
+    INTEGER(KIND=2), DIMENSION(:,:,:), INTENT(inout) :: kdta     ! new bathymetry
+
+    INTEGER :: ik,iik                   ! number of point change
+    INTEGER :: ip                       ! size of the pile
+    INTEGER :: ji, jj                   ! loop index
+    INTEGER :: ipiglo, ipjglo, ipk      ! size of the domain inferred from kdta
+    INTEGER :: iip1, iim1, ii, ij       ! working integer
+    INTEGER :: ijp1, ijm1, ikp1, ikm1
+    INTEGER(KIND=2), DIMENSION(:,:),   ALLOCATABLE :: ipile    ! pile variable
+    INTEGER(KIND=2), DIMENSION(:,:,:), ALLOCATABLE :: idata   ! new bathymetry
+    !!----------------------------------------------------------------------
+    ! infer domain size from input array
+    ipiglo = SIZE(kdta,1)
+    ipjglo = SIZE(kdta,2)
+    ipk    = SIZE(kdta,3)
+
+    ! allocate variable
+    ALLOCATE(ipile(2*ipiglo*ipjglo*ipk,3))
+    ALLOCATE(idata(ipiglo,ipjglo,ipk))
+
+    ! initialise variables
+    idata=kdta
+    ipile(:,:)=0
+    ipile(1,:)=[kiseed,kjseed,kkseed]
+    ip=1; iik=0
+
+    ! loop until the pile size is 0 or if the pool is larger than the critical size
+    DO WHILE ( ip /= 0 ) !.AND. iik < 600000);
+       iik=iik+1
+       ii=ipile(ip,1); ij=ipile(ip,2) ; ik=ipile(ip,3)
+       IF ( MOD( ip, 1000000) == 0 ) PRINT *, 'IP =', ip, iik, ii,ij, ik
+
+       ! update bathy and update pile size
+       idata(ii,ij,ik) = kifill
+       ipile(ip,:)  =[0,0,0]; ip=ip-1
+
+       ! check neighbour cells and update pile ( assume E-W periodicity )
+       iip1=ii+1; IF ( iip1 == ipiglo+1 ) iip1=2
+       iim1=ii-1; IF ( iim1 == 0        ) iim1=ipiglo-1
+       ijp1=ij+1 ; ijm1 =ij-1
+       ikp1=ik+1 ; IF (ikp1 == ipk+1 ) ikp1=ik
+       ikm1=ik-1 ; IF (ikm1 == 0     ) ikm1=ik
+
+
+       IF (idata(ii, ijp1,ik) > 0 ) THEN
+          ip=ip+1; ipile(ip,:)=[ii  ,ijp1,ik]
+       END IF
+       IF (idata(ii, ijm1,ik) > 0 ) THEN
+          ip=ip+1; ipile(ip,:)=[ii  ,ijm1,ik]
+       END IF
+
+       IF (idata(iip1, ij,ik) > 0 ) THEN
+          ip=ip+1; ipile(ip,:)=[iip1,ij  ,ik]
+       END IF
+       IF (idata(iim1, ij,ik) > 0 ) THEN
+          ip=ip+1; ipile(ip,:)=[iim1,ij  ,ik]
+       END IF
+       IF (idata(ii, ij,ikp1) > 0 ) THEN
+          ip=ip+1; ipile(ip,:)=[ii  ,ij,ikp1]
+       END IF
+
+       IF (idata(ii, ij,ikm1) > 0 ) THEN
+          ip=ip+1; ipile(ip,:)=[ii  ,ij,ikm1]
+       END IF
+
+    END DO
+
+    kdta=idata;
+
+    DEALLOCATE(ipile); DEALLOCATE(idata)
+
+  END SUBROUTINE FillPool3D
+
 END MODULE modutils
diff --git a/src/namdom_template_75 b/src/namdom_template_75
new file mode 100644
index 0000000..1ad88f7
--- /dev/null
+++ b/src/namdom_template_75
@@ -0,0 +1,45 @@
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   jpk         =    75
+   nn_bathy    =    1      !  compute (=0) or read (=1) the bathymetry file
+   rn_bathy    =    0.     !  value of the bathymetry. if (=0) bottom flat at jpkm1
+   nn_closea   =    0      !  remove (=0) or keep (=1) closed seas and lakes (ORCA)
+   nn_msh      =    0      !  create (=1) a mesh file or not (=0)
+   rn_hmin     =   -3.     !  min depth of the ocean (>0) or min number of ocean level (<0)
+   rn_e3zps_min=   20.     !  partial step thickness is set larger than the minimum of
+   rn_e3zps_rat=    0.1    !  rn_e3zps_min and rn_e3zps_rat*e3t, with 0<rn_e3zps_rat<1
+                           !
+   rn_rdt      = 5760.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+   nn_acc      =    0      !  acceleration of convergence : =1      used, rdt < rdttra(k)
+                                 !                          =0, not used, rdt = rdttra
+   rn_rdtmin   = 28800.          !  minimum time step on tracers (used if nn_acc=1)
+   rn_rdtmax   = 28800.          !  maximum time step on tracers (used if nn_acc=1)
+   rn_rdth     =  800.           !  depth variation of tracer time step  (used if nn_acc=1)
+   ln_crs      = .false.      !  Logical switch for coarsening module
+   jphgr_msh   =       0               !  type of horizontal mesh
+                                       !  = 0 curvilinear coordinate on the sphere read in coordinate.nc
+                                       !  = 1 geographical mesh on the sphere with regular grid-spacing
+                                       !  = 2 f-plane with regular grid-spacing
+                                       !  = 3 beta-plane with regular grid-spacing
+                                       !  = 4 Mercator grid with T/U point at the equator
+   ppglam0     =       0.0             !  longitude of first raw and column T-point (jphgr_msh = 1)
+   ppgphi0     =     -35.0             ! latitude  of first raw and column T-point (jphgr_msh = 1)
+   ppe1_deg    =       1.0             !  zonal      grid-spacing (degrees)
+   ppe2_deg    =       0.5             !  meridional grid-spacing (degrees)
+   ppe1_m      =    5000.0             !  zonal      grid-spacing (degrees)
+   ppe2_m      =    5000.0             !  meridional grid-spacing (degrees)
+   ppsur       =    -4762.96143546300  !  ORCA r4, r2 and r05 coefficients
+   ppa0        =      255.58049070440  ! (default coefficients)
+   ppa1        =      245.58132232490  !
+   ppkth       =       21.43336197938  !
+   ppacr       =        3.0            !
+   ppdzmin     =       10.             !  Minimum vertical spacing
+   pphmax      =     5000.             !  Maximum depth
+   ldbletanh   =    .TRUE.             !  Use/do not use double tanf function for vertical coordinates
+   ppa2        =      100.760928500000 !  Double tanh function parameters
+   ppkth2      =       48.029893720000 !
+   ppacr2      =       13.000000000000 !
+/
+

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-science/packages/cdftools.git



More information about the debian-science-commits mailing list