Browse Source

Initial fork from commit 25133a1 02/07/2018

Pierre-Yves Barriat 6 years ago
parent
commit
a43ac0a746
100 changed files with 17834 additions and 0 deletions
  1. 340 0
      LICENSE
  2. 974 0
      barakuda.sh
  3. 396 0
      build_clim.sh
  4. 162 0
      cdftools_light/Makefile
  5. 17 0
      cdftools_light/macro/macro.gfortran_ekman
  6. 17 0
      cdftools_light/macro/macro.gfortran_gustafson
  7. 15 0
      cdftools_light/macro/macro.gfortran_ubuntu
  8. 17 0
      cdftools_light/macro/macro.gfortran_vagn
  9. 9 0
      cdftools_light/macro/macro.gfortran_zenobe
  10. 13 0
      cdftools_light/macro/macro.ifort
  11. 25 0
      cdftools_light/macro/macro.ifort_beskow
  12. 23 0
      cdftools_light/macro/macro.ifort_bi
  13. 11 0
      cdftools_light/macro/macro.ifort_cca
  14. 18 0
      cdftools_light/macro/macro.ifort_marenostrum
  15. 12 0
      cdftools_light/macro/macro.ifort_rhino
  16. 8 0
      cdftools_light/macro/macro.ifort_triolith
  17. 179 0
      cdftools_light/src/cdfcurl.f90
  18. 238 0
      cdftools_light/src/cdfhflx.f90
  19. 260 0
      cdftools_light/src/cdficediags.f90
  20. 659 0
      cdftools_light/src/cdficeflux.f90
  21. 1961 0
      cdftools_light/src/cdfio.f90
  22. 241 0
      cdftools_light/src/cdfmaxmoc.f90
  23. 362 0
      cdftools_light/src/cdfmean.f90
  24. 186 0
      cdftools_light/src/cdfmeanvar.f90
  25. 358 0
      cdftools_light/src/cdfmhst.f90
  26. 290 0
      cdftools_light/src/cdfmoc.f90
  27. 197 0
      cdftools_light/src/cdfmoy.f90
  28. 205 0
      cdftools_light/src/cdfmxl.f90
  29. 192 0
      cdftools_light/src/cdfpsi.f90
  30. 92 0
      cdftools_light/src/cdfrmsssh.f90
  31. 646 0
      cdftools_light/src/cdfsigtrp.f90
  32. 574 0
      cdftools_light/src/cdftransport_test_sign.f90
  33. 833 0
      cdftools_light/src/cdftransportiz.f90
  34. 250 0
      cdftools_light/src/cdfvT.f90
  35. 178 0
      cdftools_light/src/cdfw.f90
  36. 286 0
      cdftools_light/src/cdfzonalmean.f90
  37. 340 0
      cdftools_light/src/eos.f90
  38. 1738 0
      cdftools_light/src/io_ezcdf.f90
  39. 294 0
      compare_time-series.sh
  40. 234 0
      configs/config_ORCA025_L75_T511_ece32_triolith.sh
  41. 1 0
      configs/config_ORCA025_L75_TEMPLATE.sh
  42. 233 0
      configs/config_ORCA025_L75_ece32_cca.sh
  43. 227 0
      configs/config_ORCA025_L75_etienne.sh
  44. 233 0
      configs/config_ORCA025_L75_rhino_knmi.sh
  45. 202 0
      configs/config_ORCA025_L75_v36_voima.sh
  46. 225 0
      configs/config_ORCA025_L75_valentina.sh
  47. 223 0
      configs/config_ORCA1_L42_ece22_triolith.sh
  48. 222 0
      configs/config_ORCA1_L46_ece31_valentina.sh
  49. 21 0
      configs/config_ORCA1_L46_v36_LIM2_voima.sh
  50. 202 0
      configs/config_ORCA1_L46_v36_voima.sh
  51. 228 0
      configs/config_ORCA1_L75_T255_ece32_marenostrum.sh
  52. 234 0
      configs/config_ORCA1_L75_T255_ece32_triolith.sh
  53. 221 0
      configs/config_ORCA1_L75_T255_ece32_zenobe.sh
  54. 1 0
      configs/config_ORCA1_L75_TEMPLATE.sh
  55. 233 0
      configs/config_ORCA1_L75_ece32_cca.sh
  56. 233 0
      configs/config_ORCA1_L75_v36_BSC_gustafson.sh
  57. 226 0
      configs/config_ORCA1_L75_valentina.sh
  58. 223 0
      configs/config_ORCA2_L31_ece32_marenostrum.sh
  59. 211 0
      configs/config_ORCA2_L31_v36_triolith.sh
  60. 215 0
      configs/config_eORCA1_L75_v36_voima.sh
  61. 36 0
      data/TS_sections.dat
  62. BIN
      data/basin_mask_ORCA025_ece3.2_2017.nc4
  63. BIN
      data/basin_mask_ORCA1_ece2.2_cmip5.nc4
  64. BIN
      data/basin_mask_ORCA1_ece3.2_2017.nc4
  65. 4 0
      data/def_boxes_NASST_ORCA1.txt
  66. 5 0
      data/def_boxes_convection_ORCA025_y1050.txt
  67. 14 0
      data/def_boxes_convection_ORCA1.txt
  68. 11 0
      data/def_boxes_convection_ORCA1_ece2.txt
  69. 5 0
      data/def_boxes_convection_ORCA2.txt
  70. 9 0
      data/dens_section_ORCA025_y1050.dat
  71. 9 0
      data/dens_section_ORCA1.dat
  72. 15 0
      data/dens_section_ORCA1_EXTRA.dat
  73. 7 0
      data/dens_section_ORCA2.dat
  74. 27 0
      data/ice_march_north.dat
  75. BIN
      data/obs/radsw_monthly_clim_1980-2005_NOCS2.nc4
  76. 15 0
      data/transport_ice_ORCA025_y1050.dat
  77. 15 0
      data/transport_ice_ORCA1.dat
  78. 25 0
      data/transportiz_EE3.ORCA1.dat
  79. 9 0
      data/transportiz_ORCA025.dat
  80. 23 0
      data/transportiz_ORCA025_y1050.dat
  81. 25 0
      data/transportiz_ORCA1.dat
  82. 35 0
      data/transportiz_ORCA1_ARCTIC.dat
  83. 25 0
      data/transportiz_ORCA1_COMPLETE.dat
  84. 5 0
      data/transportiz_ORCA1_FRAM+DS.dat
  85. 11 0
      data/transportiz_ORCA1_barents.dat
  86. 47 0
      data/transportiz_ORCA1_cmip5.dat
  87. 33 0
      data/transportiz_ORCA1_extra-ARCTIC.dat
  88. 25 0
      data/transportiz_ORCA1_extra-LS_square.dat
  89. 17 0
      data/transportiz_ORCA1_extra_NAtl.dat
  90. 11 0
      data/transportiz_ORCA1_light.dat
  91. 9 0
      data/transportiz_ORCA1_minimum.dat
  92. 15 0
      data/transportiz_ORCA1_old.dat
  93. 11 0
      data/transportiz_ORCA2.dat
  94. 29 0
      data/transportiz_ORCA2_all.dat
  95. 36 0
      platform/cca.job.tmpl
  96. 174 0
      platform/meta_launch_cca.sh
  97. 29 0
      platform/meta_launch_nsc.sh
  98. 78 0
      platform/meta_launch_rhino.sh
  99. 111 0
      python/exec/.old/orca025_create_basin_mask_from_meshmask.py
  100. 215 0
      python/exec/.old/orca1_create_basin_mask_from_meshmask.py

+ 340 - 0
LICENSE

@@ -0,0 +1,340 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+                            NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    {description}
+    Copyright (C) {year}  {fullname}
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  {signature of Ty Coon}, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
+

+ 974 - 0
barakuda.sh

@@ -0,0 +1,974 @@
+#!/usr/bin/env bash
+
+#==============================================================
+#
+#                    B A R A K U D A
+#
+#    An OCEAN MONITORING python environment for NEMO
+#
+#             L. Brodeau, 2009-2017
+#
+#===============================================================
+
+export script=barakuda
+[ -z ${BARAKUDA_ROOT+x} ] && export BARAKUDA_ROOT=${PWD}
+
+# Display available configs:
+list_conf="`\ls ${BARAKUDA_ROOT}/configs/config_*.sh | sed -e "s|${BARAKUDA_ROOT}/configs\/config_||g" -e s/'.sh'/''/g`"
+# User configs, potentially in the directory from which barakuda.sh is called:
+list_conf+=" `\ls ./config_*.sh 2>/dev/null | sed -e "s|.\/config_||g" -e s/'.sh'/''/g`"
+
+
+# Important bash functions:
+. ${BARAKUDA_ROOT}/src/bash/bash_functions.bash
+
+barakuda_init
+
+while getopts C:R:f:y:c:FeEh option ; do
+    case $option in
+        C) export CONFIG=${OPTARG} ;;
+        R) export EXP=${OPTARG} ;;
+        f) export IFREQ_SAV_YEARS=${OPTARG} ;;
+        y) export YEAR0=${OPTARG} ; export LFORCE_YINI=true ;;
+        c) export EXPREF=${OPTARG} ;;
+        F) export LFORCEDIAG=true ;;
+        e) export ISTAGE=2 ;;
+        E) export ISTAGE=2 ; export l_clim_diag=true ;;
+        h)  barakuda_usage; exit ;;
+        \?) barakuda_usage; exit ;;
+    esac
+done
+
+barakuda_check
+
+# Time to source the config file:
+if [ -f ./config_${CONFIG}.sh ]; then
+    # sourcing local configuration file if present:
+    fconfig=./config_${CONFIG}.sh
+else
+    # sourcing barakuda-distribution configuration file:
+    fconfig=${BARAKUDA_ROOT}/configs/config_${CONFIG}.sh
+fi
+if [ -f ${fconfig} ]; then
+    echo "Sourcing configuration file: ${fconfig} !"
+    . ${fconfig}
+else
+    echo "ERROR: cannot find file ${fconfig} !"; exit
+fi
+echo
+
+
+
+
+# If auto-submit experiment (ece_exp=10) then overides a few functions with:
+if [ ${ece_exp} -ge 10 ]; then
+    echo "Sourcing ${BARAKUDA_ROOT}/src/bash/bash_functions_autosub.bash"
+    . ${BARAKUDA_ROOT}/src/bash/bash_functions_autosub.bash
+fi
+
+
+# If 3D fieds are annual averaged then overides a few functions with:
+if [ ! "${ANNUAL_3D}" = "" ]; then
+    . ${BARAKUDA_ROOT}/src/bash/bash_functions_1y.bash
+fi
+
+# List of CDFTOOLS executables needed for the diagnostics:
+export L_EXEC="cdfmaxmoc.x cdfmoc.x cdfvT.x cdftransportiz.x cdficeflux.x cdficediags.x cdfmhst.x cdfsigtrp.x"
+
+barakuda_setup
+
+echo
+echo " SETTINGS: "
+echo "   *** CONFIG     = ${CONFIG} "
+echo "   *** NEMO_OUT_D = ${NEMO_OUT_D} "
+echo "   *** CLIM_DIR   = ${CLIM_DIR} "
+echo "   *** TMP_DIR    = ${TMP_DIR} "
+echo "   *** GRID       = ${ORCA} "
+echo "   *** EXP        = ${EXP} "
+echo "   *** CPREF      = ${CPREF} "
+echo "   *** IFREQ_SAV_YEARS = ${IFREQ_SAV_YEARS} "
+echo "   *** NCDF_DIR        = ${NCDF_DIR} "
+echo
+
+
+if [ ${ISTAGE} -eq 1 ]; then
+    barakuda_first_last_years ; # look at NEMO files to know what are first and last years available...
+    echo ${IFREQ_SAV_YEARS} > ${DIAG_D}/numb_year_per_file.info
+    echo ${YEAR_INI}        > ${DIAG_D}/first_year.info
+else
+    # -> this is stage 2 (plot generation) ISTAGE=2 !
+    barakuda_init_plot
+fi
+
+cyear_ini=`printf "%04d" ${YEAR_INI}`
+cyear_end=`printf "%04d" ${YEAR_END}`
+
+# For proper python executables and scripts to be found:
+export PATH=${PYBRKD_EXEC_PATH}:${BARAKUDA_ROOT}/src/bash:${PYTHON_HOME}/bin:${PATH}
+
+#                                   setup over
+######################################################################################
+
+
+
+jyear=${YEAR_INI}
+
+fcompletion=${DIAG_D}/last_year_done.info
+if [ -f ${fcompletion} ]; then jyear=`cat ${fcompletion}`; ((jyear++)); fi
+
+cd ${TMP_DIR}/
+
+barakuda_import_mesh_mask ; # Importing mesh_mask (+basin) files...
+
+if [ ${ISTAGE} -eq 1 ]; then
+    # Importing cdftools executables:
+    for ex in ${L_EXEC}; do rsync -v ${BARAKUDA_ROOT}/cdftools_light/bin/${ex} . ; done
+fi
+
+
+
+
+# L O O P   A L O N G   Y E A R S
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+lcontinue=true
+
+if ${LFORCEDIAG}; then lcontinue=false; fi
+
+while ${lcontinue}; do
+
+    export cyear=`printf "%04d" ${jyear}`
+    cpf=""
+    if [ ${ISTAGE} -eq 1 ] && [ ${ece_exp} -gt 0 ]; then
+        iy=$((${jyear}-${YEAR_INI}+1+${YEAR_INI}-${YEAR_INI_F}))
+        dir_ece=`printf "%03d" ${iy}`
+        echo " *** ${cyear} => dir_ece = ${dir_ece}"
+        cpf="${dir_ece}/"
+    fi
+
+    i_get_file=0
+    if [ $((${jyear}%${IFREQ_SAV_YEARS})) -eq 0 ]; then
+        barakuda_check_year_is_complete  ; # lcontinue might be updated to false!
+    fi    
+    echo; echo
+    
+    export CRT1M=${CPREF}${cyear}${cmmdd1}_${cyear}${cmmdd2}
+    if ${l_y2_j}; then export CRT1M=${CPREF}${cyear}${cmmdd1}_`printf "%04d" $((${jyear}+1))`${cmmdd2} ; fi
+    
+    if ${lcontinue}; then
+
+        echo "Yeah! Year ${jyear} is saved..."; echo
+
+        
+        if [ ${ISTAGE} -eq 2 ]; then
+            echo; echo "You cannot create figures and HTML pages yet!"
+            echo " => finish treating the results first by launching barakuda.sh without the '-e' switch."
+            exit
+        fi
+        
+        echo; echo
+        echo "*********************************************************************"
+        echo "  Experiment ${EXP}: Will generate diagnostics and data for year ${cyear}..."
+        echo "*********************************************************************"
+        echo; echo
+
+        barakuda_import_files
+        
+        # Monthly files to work with for current year:
+        ft1m=${CRT1M}_grid_T.nc
+        fu1m=${CRT1M}_grid_U.nc
+        fv1m=${CRT1M}_grid_V.nc
+        fj1m=${CRT1M}_${FILE_ICE_SUFFIX}.nc ; # can be icemod or grid_T ....
+        ff1m=${CRT1M}_${FILE_FLX_SUFFIX}.nc ; # file with surface fluxes
+        #
+        # Annual files to work with for current year:
+        CRT1Y=`echo ${CRT1M} | sed -e s/"_${TSTAMP}_"/"_${ANNUAL_3D}_"/g`
+        ft1y=${CRT1Y}_grid_T.nc
+        fu1y=${CRT1Y}_grid_U.nc
+        fv1y=${CRT1Y}_grid_V.nc
+        fj1y=${CRT1Y}_${FILE_ICE_SUFFIX}.nc
+        ff1y=${CRT1Y}_${FILE_FLX_SUFFIX}.nc
+        CFG3D=${CRT1M}
+        #
+        # Files that contain the 3D fields (might be monthly or annaual sometimes (when "${ANNUAL_3D}" = "1y")        
+        ft3d=${ft1m}
+        fu3d=${fu1m}
+        fv3d=${fv1m}
+        if [ "${ANNUAL_3D}" = "1y" ]; then
+            [[ ${NEMO_SAVED_FILES_3D} =~ (^|[[:space:]])"grid_U"($|[[:space:]]) ]] \
+                && CFG3D=${CRT1Y}; ft3d=${ft1y}; fu3d=${fu1y}; fv3d=${fv1y} \
+                || echo "...default"
+            echo ""
+        fi
+        fvt=${CFG3D}_VT.nc
+        
+
+        # -- time to compute diagnostics --
+
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        # If coupled EC-Earth simu, attempting to compute ocean-averaged fluxes from IFS too (E, P, E-P)
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        if [ ${ece_exp} -eq 2 ] && [ ${NBL} -eq 75 ] && [ ${i_do_ifs_flx} -eq 1 ]; then
+            echo; echo; echo "Fluxes of freshwater at the surface from IFS..."
+            echo " *** CALLING: extract_ifs_surf_fluxes.sh &"
+            extract_ifs_surf_fluxes.sh &
+            pid_flxl=$! ; echo
+        fi
+
+
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        # Computing time-series of spatially-averaged variables
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        if [ ${i_do_mean} -eq 1 ]; then
+            #
+            echo; echo "3D-averaging for time series"
+            echo " *** CALLING: mean_3d.py ${ft1m} ${jyear} T &"
+            mean_3d.py ${ft1m} ${jyear} T &
+            pid_mn3dt=$! ; echo
+            #
+            echo " *** CALLING: mean_3d.py ${ft1m} ${jyear} S &"
+            mean_3d.py ${ft1m} ${jyear} S &
+            pid_mn3ds=$! ; echo
+            #
+            echo; echo "2D-averaging for time series"
+            echo " *** CALLING: mean_2d.py ${ft1m} ${jyear} &"
+            mean_2d.py ${ft1m} ${jyear} &
+            pid_mn2d=$! ; echo
+            #
+            echo; echo "2D-integration of some surface fluxes over basins"
+            echo " *** CALLING: flux_int_basins.py ${ff1m} ${jyear} &"
+            flux_int_basins.py ${ff1m} ${jyear} &
+            pid_ssf=$! ; echo
+            #
+        fi
+        
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~
+        # Creating VT file if needed
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~
+        if [ ${i_do_trsp} -gt 0 ] || [ ${i_do_mht} -eq 1 ]; then
+            if [ ! -f ${fvt} ]; then
+                echo; echo; echo " *** CALLING: ./cdfvT.x ${CFG3D} ${NN_T} ${NN_S} ${NN_U} ${NN_V} ${NN_U_EIV} ${NN_V_EIV} &"
+                ./cdfvT.x ${CFG3D} ${NN_T} ${NN_S} ${NN_U} ${NN_V} ${NN_U_EIV} ${NN_V_EIV} &
+                pid_vtvt=$! ; echo
+            fi
+        fi
+
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        # 2D maps of NEMO - OBS for SST and SSS (for movies)
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        if [ ${i_do_movi} -eq 1 ]; then
+            echo; echo; echo "2D maps of NEMO - OBS for SST and SSS (for movies)"
+            echo " *** CALLING: prepare_movies.py ${ft1m} ${jyear} sst &"
+            prepare_movies.py ${ft1m} ${jyear} sst &
+            pid_movt=$! ; echo
+            echo " *** CALLING: prepare_movies.py ${ft1m} ${jyear} sss &"
+            prepare_movies.py ${ft1m} ${jyear} sss &
+            pid_movs=$! ; echo
+            echo " *** CALLING: prepare_movies.py ${ft1m} ${jyear} mld &"
+            prepare_movies.py ${ft1m} ${jyear} mld &
+            pid_movm=$! ; echo
+            echo " *** CALLING: prepare_movies.py ${fj1m} ${jyear} ice &"
+            prepare_movies.py ${fj1m} ${jyear} ice &
+            pid_movi=$! ; echo
+        fi        
+
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        # Computing time-series of spatially-averaged variables
+        # on boxes (saving the variable on 2D box too...
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        if [ ${i_do_ssx_box} -eq 1 ]; then
+            echo; echo; echo "Box monthly values"
+            echo " *** CALLING: ssx_boxes ${ft1m} ${jyear} ${NN_SST} ${NN_SSS} &"
+            ssx_boxes.py ${ft1m} ${jyear} ${NN_SST} ${NN_SSS} &
+            pid_boxa=$! ; echo
+        fi
+
+        #~~~~~~~
+        #  MOC
+        #~~~~~~~
+        if [ ${i_do_amoc} -eq 1 ]; then
+            echo; echo; echo "MOC"
+            rm -f moc.nc *.tmp
+            echo " *** CALLING: ./cdfmoc.x ${fv3d} ${NN_V} ${NN_V_EIV} &"
+            ./cdfmoc.x ${fv3d} ${NN_V} ${NN_V_EIV} &
+            pid_amoc=$! ; echo
+        fi
+
+        #~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        #  Transport by sigma-class
+        #~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        if [ ${i_do_sigt} -eq 1 ]; then
+            echo; echo
+            if [ ! -f ./dens_section.dat ]; then
+                if [ -f ${DENSITY_SECTION_FILE} ]; then
+                    echo "Copying ${DENSITY_SECTION_FILE} to here: `pwd` !"; cp ${DENSITY_SECTION_FILE} ./dens_section.dat
+                else
+                    echo; echo "WARNING: Can't do Transport by sigma-class: ${DENSITY_SECTION_FILE} is missing!!!"
+                fi
+            fi
+            echo " *** CALLING: ./cdfsigtrp.x ${ft3d} ${fu3d} ${fv3d} 24.8 28.6 19 ${jyear} ${DIAG_D}  ${NN_T} ${NN_S} ${NN_U} ${NN_V} &"; echo
+            ./cdfsigtrp.x ${ft3d} ${fu3d} ${fv3d} 24.8 28.6 19 ${jyear} ${DIAG_D} ${NN_T} ${NN_S} ${NN_U} ${NN_V} &
+            pid_sigt=$! ; echo
+        fi
+
+        echo
+        echo " Gonna wait for level #1 to be done !"
+        wait ${pid_vtvt}
+        #wait
+        echo " .... diag level #1 done...." ; echo        
+        echo
+
+
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        # Meridional heat and salt transport
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        if [ ${i_do_mht} -eq 1 ]; then
+            echo; echo; echo "Meridional transport of heat and salt"
+            fo=${DIAG_D}/merid_transport_T_S_${CONFEXP}.nc
+            if [ ! -f ${fvt} ]; then
+                echo "WARNING: file ${fvt} is not here, skipping meridional transports section"
+            else
+                rm -f merid_heat_trp.dat merid_salt_trp.dat
+                echo " *** CALLING: ./cdfmhst.x ${fvt} ${fo} ${jyear} &"
+                ./cdfmhst.x ${fvt} ${fo} ${jyear} &
+                pid_mhst=$! ; echo
+            fi
+        fi
+                
+        
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        # VOLUME, HEAT and SALT transports through specified section
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        if [ ${i_do_trsp} -gt 0 ]; then
+            echo; echo; echo "Transports of volume, heat and salt through different sections"
+            if [ -z ${TRANSPORT_SECTION_FILE} ]; then
+                echo "Please specify which TRANSPORT_SECTION_FILE to use into the config file!" ; exit
+            fi
+            if [ ! -f ./transportiz.dat ]; then
+                check_if_file ${TRANSPORT_SECTION_FILE}
+                cp ${TRANSPORT_SECTION_FILE} ./transportiz.dat
+            fi
+            if [ ${i_do_trsp} -eq 1 ]; then z1_trsp="" ; z2_trsp=""; fi
+            if [ ! -f ${fvt} ]; then
+                echo "WARNING: file ${fvt} is not here, skipping transport section!"
+            else
+                # Breaking transportiz file in several files so we can go parallel!
+                rm -f transportiz_*.dat
+                break_downn_section_file.py ./transportiz.dat 2 ; # => Max. 2 sections per file
+                list=`\ls transportiz_*.dat`
+                for fs in ${list}; do
+                    echo " *** CALLING: ./cdftransportiz.x ${fs} ${CFG3D} ${NN_U} ${NN_V} ${NN_U_EIV} ${NN_V_EIV} ${jyear} ${DIAG_D} ${z1_trsp} ${z2_trsp} &"
+                    ./cdftransportiz.x ${fs} ${CFG3D} ${NN_U} ${NN_V} ${NN_U_EIV} ${NN_V_EIV} ${jyear} ${DIAG_D} ${z1_trsp} ${z2_trsp} &
+                    echo
+                done
+            fi
+        fi
+
+        
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        # Solid freshwater transport through sections due to sea-ice drift
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        if [ ${i_do_ice} -gt 0 ] && [ ${i_do_trsp_ice} -eq 1 ]; then
+            echo; echo; echo "Solid freshwater transport through sections due to sea-ice drift"
+            if [ -z ${TRANSPORT_SECTION_FILE_ICE} ]; then
+                echo "Please specify which TRANSPORT_SECTION_FILE_ICE to use into the config file!" ; exit
+            fi
+            if [ ! -f ./transport_ice.dat ]; then
+                check_if_file ${TRANSPORT_SECTION_FILE_ICE}
+                cp ${TRANSPORT_SECTION_FILE_ICE} ./transport_ice.dat
+            fi
+            #
+            # Breaking transportiz file in several files so we can go parallel!
+            rm -f transport_ice_*.dat
+            break_downn_section_file.py ./transport_ice.dat 2 ; # => Max. 2 sections per file
+            list=`\ls transport_ice_*.dat`
+            for fs in ${list}; do
+                echo " *** CALLING: ./cdficeflux.x ${fs} ${fj1m} ${NN_ICEF} ${NN_ICEU} ${NN_ICEV} ${NN_ICET} ${jyear} ${DIAG_D} &"
+                ./cdficeflux.x ${fs} ${fj1m} ${NN_ICEF} ${NN_ICEU} ${NN_ICEV} ${NN_ICET} ${jyear} ${DIAG_D} &
+                echo
+            done
+        fi
+
+        
+        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        #  Deep Mixed Volume (DMV) on a given box
+        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        if [ ! -z ${i_do_dmv} ] && [ ${i_do_dmv} -gt 0 ]; then
+
+            if [ -z ${FILE_DEF_BOXES} ]; then
+                echo "Please specify a FILE_DEF_BOXES to use into the config file!" ; exit
+            fi
+            echo " *** CALLING: dmv.py ${ft1m} ${cyear} &"
+            dmv.py ${ft1m} ${cyear} &
+            pid_dmvl=$! ; echo
+        fi
+
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        # Budget and other stuffs on a given rectangular box!
+        # It provides time-series depending only on time (not depth)
+        # budget_rectangle_box.py
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+        if [ ${i_do_bb} -gt 0 ]; then
+
+            echo; echo; echo "Budget and other stuffs on rectangular boxes!"
+
+            if [ -z ${FILE_DEF_BOXES} ]; then
+                echo "Please specify a FILE_DEF_BOXES to use into the config file!" ; exit
+            fi
+            echo " *** CALLING: budget_rectangle_box.py ${cyear} 100 uv &"
+            budget_rectangle_box.py ${cyear} 100 uv &
+            pid_bbbb=$! ; echo
+        fi
+
+        echo " Gonna wait for level #2 to be done !"
+        wait ${pid_amoc} ; # moc needs to be done to call cdfmaxmoc.x ...
+        echo
+        echo " .... diag level #2 done...." ; echo ; echo
+
+
+
+        #~~~~~~~~~~~
+        #  Max AMOC
+        #~~~~~~~~~~~
+        if [ ${i_do_amoc} -eq 1 ]; then
+            if [ -z "${LMOCLAT}" ]; then
+                echo "AMOC => specify latitude bands with variable LMOCLAT into the config file!!!"; exit
+            fi
+            for clat in ${LMOCLAT}; do
+                cslat=`echo ${clat} | sed -e s/'-'/' '/g`
+                echo "  *** ./cdfmaxmoc.x moc.nc atl ${cslat} 500 1500 ${jyear} ${DIAG_D}"
+                ./cdfmaxmoc.x moc.nc atl ${cslat} 500 1500 ${jyear} ${DIAG_D}
+            done
+        fi
+
+
+        #~~~~~~~~~
+        # SEA-ICE
+        #~~~~~~~~~
+        if [ ${i_do_ice} -eq 1 ]; then
+            echo; echo; echo "Sea-ice extent and volume..." ; rm -f tmp_ice.nc
+            echo "ncks  -A -v ${NN_ICEF} ${fj1m} -o tmp_ice.nc"
+            ncks  -A -v ${NN_ICEF} ${fj1m} -o tmp_ice.nc
+            ncrename -v ${NN_ICEF},ice_frac tmp_ice.nc
+            coic=""
+            if [ -z ${NN_ICET} ]; then
+                coic="oic" ; # means only ice concentration available!
+            else
+                echo "ncks  -A -v ${NN_ICET} ${fj1m} -o tmp_ice.nc"
+                ncks  -A -v ${NN_ICET} ${fj1m} -o tmp_ice.nc
+                ncrename -v ${NN_ICET},ice_thic tmp_ice.nc
+            fi
+            echo " *** CALLING: ./cdficediags.x tmp_ice.nc ${jyear} ${DIAG_D} ${coic} &"
+            ./cdficediags.x tmp_ice.nc ${jyear} ${DIAG_D} ${coic} &
+
+        fi
+
+        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        # Temperature and Salinity on cross meridional/zonal sections
+        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        if [ ${i_do_sect} -eq 1 ]; then
+            check_if_file ${TS_SECTION_FILE}
+	    lst_sec=`cat ${TS_SECTION_FILE} | grep -v -E '(^#|EOF)' | awk -F ' ' '{print $1}'`
+            echo; echo; echo "Cross-sections on specified transects:"
+            echo "${lst_sec}"; echo
+            echo " *** CALLING: cross_sections.py ${ft3d} ${jyear} &"
+            cross_sections.py ${ft3d} ${jyear} &
+            echo
+        fi
+
+        
+        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        #  Vertical profiles of T,S and density horizontally averaged
+        #  on rectangular boxes defined into FILE_DEF_BOXES
+        #   => creates time-series function of time and depth
+        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        if [ ${i_do_box_TS_z} -gt 0 ]; then
+            if [ -z ${FILE_DEF_BOXES} ]; then
+                echo "Please specify a FILE_DEF_BOXES to use into the config file!" ; exit
+            fi
+            echo " *** CALLING: prof_TS_z_box.py ${cyear} &"
+            prof_TS_z_box.py ${cyear} &
+            echo;echo
+        fi
+
+
+
+
+
+        
+        # --- end of stuffs that can be launched in bg ---
+
+
+        echo
+        echo " Waiting for backround jobs for current year (${jyear}) !"
+        wait  ${pid_mn3dt} ${pid_mn3ds} ${pid_movt} ${pid_movs} ${pid_movm} ${pid_movi} ${pid_mn2d} ${pid_ssf} ${pid_flxl}
+        wait
+        echo "  Done waiting for year ${cyear} !"
+        if [ ${i_do_movi} -eq 1 ]; then rsync -rv movies ${DIAG_D}/ ; fi
+        rm -f *.tmp broken_line_* tmp_ice.nc
+        rm -f ${CRT1M}_*.nc ${CRT1Y}_*.nc ; #debug
+        echo
+
+        echo " ---- DIAGS ARE DONE FOR YEAR ${cyear} ! ---"
+        echo "${cyear}" > ${fcompletion}
+        echo; echo
+
+    fi ; # if ${lcontinue}; then
+
+
+    #if ${LFORCE_YEND}; then
+    #    if [ ${jyear} -eq ${YEARN} ]; then lcontinue=false; fi
+    #fi
+
+    wait
+
+    ((jyear++))
+
+
+# end loop years...
+done ; # while ${lcontinue}; do
+
+
+
+
+# PREPARING HTML PAGE
+# ~~~~~~~~~~~~~~~~~~~
+
+l_pclim=false
+
+if [ ${ISTAGE} -eq 2 ]; then
+
+    rm -rf ${DIAG_D}/${EXP}
+    
+    y1=`cat ${DIAG_D}/first_year.info`
+    y2=`cat ${DIAG_D}/last_year_done.info`
+    nby=$((${y2}-${y1}+1))
+
+    # Agreement between last year from output files and 'fcompletion' file:
+    ydum=`cat ${fcompletion}`
+    if [ -z ${YEARN} ]; then
+        # (if YEARN is not set...)
+        if [ ! ${ydum} -eq ${YEAR_END} ]; then
+            echo;
+            echo "###################################################################"
+            echo "ERROR: in ${fcompletion} last_year = ${ydum}"
+            echo "         and from stored files files last_year = ${YEAR_END} !"
+            echo "###################################################################"
+            echo
+            exit
+        fi
+    fi
+
+
+    
+
+    echo; echo; echo "EXP ${EXP}: creating plots"; echo
+
+    #cd ${BARAKUDA_ROOT}/
+
+    cd ${DIAG_D}/
+
+    echo
+    if [ ${i_do_movi} -eq 1 ]; then
+        if [ "${iffmpeg_x264}" = "1" ]; then
+            # FFMPEG compiled with x264 mp4 support is available on host:
+            cd movies/
+            for cc in dsst dsss mld icen ices; do
+                hh=520 ; # height of image in pixels
+                if [ "${cc}" = "icen" ]; then hh=576; fi
+                if [ "${cc}" = "ices" ]; then hh=456; fi
+                echo " *** CALLING: images2mp4.sh ${cc} ${FIG_FORM} ${hh} 8 &"
+                images2mp4.sh ${cc} ${FIG_FORM} ${hh} 8 &
+                echo
+            done
+            cd ${DIAG_D}/
+        else
+            # Faling back on GIF, with 'convert' of imageMagick:
+            idelay=$((120-${nby}*8))
+            if [ ${idelay} -lt 10 ]; then idelay=10; fi
+            rm -f *_${CONFEXP}.gif
+            for cc in dsst dsss mld icen ices; do
+                echo " *** CALLING: convert -delay ${idelay} -loop 0 movies/${cc}_*.png ${cc}_${CONFEXP}.gif &"
+                convert -delay ${idelay} -loop 0 movies/${cc}_*.png ${cc}_${CONFEXP}.gif &
+                echo
+            done
+        fi
+    fi
+    
+
+    # 1D plots to perform
+    # ~~~~~~~~~~~~~~~~~~~
+
+    DIAG_1D_LIST=""
+
+    if [ ${i_do_mean} -eq 1 ]; then
+        DIAG_1D_LIST="${DIAG_1D_LIST} 3d_so mean_sos 3d_thetao mean_tos mean_zos"
+        if [ ! "${NN_MLD}"  = "X" ]; then DIAG_1D_LIST="${DIAG_1D_LIST} mean_mld"; fi
+        if [ ! "${NN_QNET}" = "X" ]; then DIAG_1D_LIST="${DIAG_1D_LIST} mean_htf"; fi
+        if [ ! "${NN_FWF}"  = "X" ]; then DIAG_1D_LIST="${DIAG_1D_LIST} mean_fwf"; fi
+    fi
+    if [ ${i_do_amoc} -eq 1 ]; then DIAG_1D_LIST="${DIAG_1D_LIST} amoc";        fi
+    if [ ${i_do_ice}  -eq 1 ]; then DIAG_1D_LIST="${DIAG_1D_LIST} seaice";      fi
+    if [ ${i_do_trsp} -gt 0 ] || [ ${i_do_trsp_ice} -eq 1 ]; then DIAG_1D_LIST="${DIAG_1D_LIST} transport_sections" ; fi
+
+    dy=$((${YEAR_END}-${YEAR_INI}+1)) ; export YF2=$((${YEAR_END}+1))
+
+
+    # Doing 1D plots
+    # ~~~~~~~~~~~~~~    
+
+    echo ; echo; echo "Going to perform the following 1D plots:"
+    echo "    => ${DIAG_1D_LIST}"; echo
+
+    for fd in ${DIAG_1D_LIST}; do
+        echo " *** CALLING: plot_time_series.py ${fd}"
+        plot_time_series.py ${fd} ; echo
+        echo
+    done
+    echo ; echo ; echo
+
+    if [ ${i_do_mean} -eq 1 ]; then
+        
+        # 5-month-running mean SST anomaly over Nino region 3.4 graph:
+        echo " *** CALLING: plot_enso.py Nino34_${CONFEXP}.nc ${NN_SST}"
+        plot_enso.py Nino34_${CONFEXP}.nc ${NN_SST}
+        echo; echo
+
+        # Hovmuller of temperature and salinity
+        echo " *** CALLING: plot_hovm_tz.py"
+        plot_hovm_tz.py
+        echo; echo
+        
+        if [ ${nby} -ge 70 ]; then
+            # AMO aka 11-year-running mean SST anomaly over North Atlantic (0-70N)
+            echo " *** CALLING: plot_amo.py mean_SST_NAtl_${CONFEXP}.nc ${NN_SST}"
+            plot_amo.py mean_SST_NAtl_${CONFEXP}.nc ${NN_SST}
+            echo; echo
+        fi        
+    fi
+
+
+    if [ ${i_do_sigt} -eq 1 ]; then
+        # Transport by sigma-class
+        echo " *** CALLING: plot_trsp_sigma.py"
+        plot_trsp_sigma.py
+        echo; echo; echo
+    fi
+
+
+    if [ ${i_do_mht} -eq 1 ]; then
+        #
+        # Hovmullers of advective meridional heat/salt transport
+        echo; echo
+        echo " *** CALLING: plot_hovm_merid_trsp.py"
+        plot_hovm_merid_trsp.py
+        echo; echo; echo
+        #
+    fi
+
+
+
+    echo; echo; echo
+
+
+
+
+    if ${l_clim_diag} ; then
+
+        ###########################################################################
+        # Climatology over X years (12-month file average of X consecutive years)
+        #   => has to be built with the 'build_clim.sh' script
+        ###########################################################################
+
+        echo; echo; echo "Checking for presence of ${DIAG_D}/clim/last_clim..."
+        if [ -f ${DIAG_D}/clim/last_clim ]; then
+            cat ${DIAG_D}/clim/last_clim
+            export CLIM_PER=`cat ${DIAG_D}/clim/last_clim`
+            ftcli=${DIAG_D}/clim/mclim_${CONFEXP}_${CLIM_PER}_grid_T.nc4
+            ficli=${DIAG_D}/clim/mclim_${CONFEXP}_${CLIM_PER}_${FILE_ICE_SUFFIX}.nc4
+            fcsbc=${DIAG_D}/clim/mclim_${CONFEXP}_${CLIM_PER}_${FILE_FLX_SUFFIX}.nc4
+            fclvt=${DIAG_D}/clim/aclim_${CONFEXP}_${CLIM_PER}_VT.nc4
+            fcmoc=${DIAG_D}/clim/aclim_${CONFEXP}_${CLIM_PER}_MOC.nc4
+            fcpsi=${DIAG_D}/clim/aclim_${CONFEXP}_${CLIM_PER}_PSI.nc4
+            fccrl=${DIAG_D}/clim/aclim_${CONFEXP}_${CLIM_PER}_TCURL.nc4
+            iclyear=`echo ${CLIM_PER} | sed -e s/'-'/' '/g`
+        else
+            echo; echo "ERROR => you set l_clim_diag to true (probably by using '-E') but no file 'last_clim' was found in:"
+            echo "               ${DIAG_D}/clim/"
+            echo "               => then use '-e' instead!"; echo
+            exit
+        fi
+
+        echo; echo; echo "Checking for presence of ${ftcli}..."
+        if [ -f ${ftcli} ]; then
+            echo; echo;
+            echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~"
+            echo "*   Climatologies found !!!"
+            echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~"
+            echo
+            echo "  => for years ${CLIM_PER}" ; echo "  => using ${ftcli}"
+
+            list_comp_2d="OBS"
+            l_pclim=true
+            lcomp_to_exp=false
+
+            if [ ! -z ${EXPREF} ]; then
+                lcomp_to_exp=true
+                list_comp_2d="OBS ${EXPREF}"
+                # Must check if climatology for exp ${EXPREF} is there:
+                fclim_ref=`echo "${ftcli}" | sed -e "s|${EXP}|${EXPREF}|g"`
+                check_if_file ${fclim_ref}
+                echo "Going to compare also against exp ${fclim_ref}!"
+                echo
+            fi
+
+            echo; echo
+            for ff in ${F_T_OBS_3D_12} ${F_S_OBS_3D_12} ${F_SST_OBS_12}; do check_if_file ${ff} "name:${ff}"; done
+            if [ ${i_do_ice} -gt 0 ]; then check_if_file ${F_ICE_OBS_12}    "name:${F_ICE_OBS_12}" ; fi
+            echo; echo
+
+
+            #######################################
+            # Diags that don't imply a comparison #
+            #######################################
+
+            export COMP2D="OBS"
+            
+            # Lat-Depth AMOC
+            # ~~~~~~~~~~~~~~
+            if [ -f ${fcmoc} ]; then
+                echo; echo
+                echo " Ploting lat-depth MOC !"
+                cd ${DIAG_D}/
+                export DIRS_2_EXP="${DIRS_2_EXP} moc"
+                rm -rf moc; mkdir moc; cd moc/
+                echo; echo; echo " *** CALLING: moc.py ${iclyear}"
+                moc.py ${iclyear} &
+                cd ../
+                echo
+            fi
+
+            # March Mixed layer depth in Nordic Seas
+            # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+            if [ `ipresent_var_in_ncf ${ftcli} ${NN_MLD}` -eq 1 ]; then
+                echo; echo
+                echo " Performing 2D mapping of March Mixed layer depth in Nordic Seas"
+                cd ${DIAG_D}/
+                export DIRS_2_EXP="${DIRS_2_EXP} mld"
+                rm -rf mld; mkdir mld; cd mld/
+                echo; echo; echo " *** CALLING: mld.py ${iclyear}"; echo
+                mld.py ${iclyear} &
+                cd ../
+                echo
+            fi
+
+            # Sea-ice extent stereographic polar projection South and North
+            # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+            if [ ${i_do_ice}  -gt 0 ] && [ `ipresent_var_in_ncf ${ficli} ${NN_ICEF}` -eq 1 ]; then
+                echo; echo
+                echo " Performing 2D Sea-ice extent stereographic polar projection South and North"
+                cd ${DIAG_D}/
+                export DIRS_2_EXP="${DIRS_2_EXP} sea_ice"
+                rm -rf sea_ice; mkdir sea_ice; cd sea_ice/
+                echo; echo; echo " *** CALLING: ice.py ${iclyear}"; echo
+                ice.py ${iclyear} &
+                cd ../
+                echo
+            fi
+
+            # Sea-surface height
+            # ~~~~~~~~~~~~~~~~~~
+            if [ `ipresent_var_in_ncf ${ftcli} ${NN_SSH}` -eq 1 ]; then
+                echo; echo; echo " SSH map"
+                export DIRS_2_EXP="${DIRS_2_EXP} ssh"
+                cd ${DIAG_D}/
+                rm -rf ssh; mkdir ssh; cd ssh/
+                echo " *** CALLING: ssh.py ${iclyear}"; echo
+                ssh.py ${iclyear} &
+                cd ../ ;  echo
+            else
+                echo; echo "WARNING: did not find ${NN_SSH} into ${ftcli} !!!!"; echo
+            fi
+            
+            # Wind-stress module and curl
+            # ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+            if [ -f ${fccrl} ]; then
+                echo; echo; echo " Wind-stress module and curl maps"
+                if [ -x ${NN_TAUM} ]; then echo "ERROR: define variable NN_TAUM in ${fconfig}! ('X' if not present in NEMO output)"; exit; fi
+                export DIRS_2_EXP="${DIRS_2_EXP} wind"
+                cd ${DIAG_D}/
+                rm -rf wind; mkdir wind; cd wind/
+                echo " *** CALLING: wind.py ${iclyear}"; echo
+                wind.py ${iclyear} &
+                cd ../ ;  echo
+            else
+                echo
+                echo "WARNING: did not find file ${fccrl} !!!"
+                echo "         or did not find ${NN_TAUM} into ${fcsbc} !!!!"
+                echo
+            fi
+            
+
+            # Zonally-averaged surface heat fluxes
+            # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ lolo
+            if [ -f ${fcsbc} ]; then
+                echo; echo; echo " Zonally-averaged surface heat fluxes"
+                if [ -x ${NN_QSOL} ]; then echo "ERROR: define variable NN_QSOL in ${fconfig}! ('X' if not present in NEMO output)"; exit; fi
+                export DIRS_2_EXP="${DIRS_2_EXP} sfluxes"
+                cd ${DIAG_D}/
+                rm -rf sfluxes; mkdir sfluxes; cd sfluxes/
+                echo " *** CALLING: sfluxes.py ${iclyear}"; echo
+                sfluxes.py ${iclyear} &
+                cd ../ ;  echo
+            else
+                echo
+                echo "WARNING: did not find file ${fcsbc} !!!"
+                echo "         or did not find ${NN_QSOL} into ${fcsbc} !!!!"
+                echo
+            fi
+            
+
+            ##################################################
+            # Diags that imply a comparison against "COMP2D" #
+            ##################################################
+
+            cd ${DIAG_D}/
+            rm -rf temp_sal
+
+            for COMP2D in ${list_comp_2d}; do
+
+                export COMP2D=${COMP2D}
+                echo; echo; echo "Clim. comparisons against ${COMP2D}"
+               
+                if [ "${COMP2D}" = "${EXPREF}" ]; then
+                    export F_T_OBS_3D_12=${fclim_ref}; check_if_file ${F_T_OBS_3D_12} "name:F_T_OBS_3D_12"
+                    export F_S_OBS_3D_12=${fclim_ref}; check_if_file ${F_S_OBS_3D_12} "name:F_S_OBS_3D_12"
+                    export F_SST_OBS_12=${fclim_ref} ; check_if_file ${F_SST_OBS_12}  "name:F_SST_OBS_12"
+                    if [ ${i_do_ice}  -gt 0 ]; then export F_ICE_OBS_12=${fclim_ref}   ; check_if_file ${F_ICE_OBS_12}    "name:F_ICE_OBS_12"; fi
+                fi
+                
+                # Temperature and Salinity
+                # ~~~~~~~~~~~~~~~~~~~~~~~~
+                echo; echo
+                echo " Creating maps and cross-sections (i_do_sect) of Temperature and Salinity"
+                cd ${DIAG_D}/
+                export DIRS_2_EXP="${DIRS_2_EXP} temp_sal"
+                DIRS_2_EXP_RREF="${DIRS_2_EXP_RREF} temp_sal"
+                mkdir -p temp_sal; cd temp_sal/
+                echo; echo; echo " *** CALLING: temp_sal.py ${iclyear} &"; echo
+                temp_sal.py ${iclyear} &
+                cd ../
+                echo
+                
+            done ; # for COMP2D in ${list_comp_2d}; do
+
+            wait
+            
+        else
+            echo; echo
+            echo " No Climatologies found ...";
+            echo "   => you can use 'build_clim.sh' to build a climato of your experiment"
+            echo; echo
+        fi
+
+    fi ; # if ${l_clim_diag}
+
+
+    
+    wait
+
+
+    # Time for HTML stuff!
+
+    export HTML_DIR=${DIAG_D}/${EXP}
+    mkdir -p ${HTML_DIR}
+    
+    cd ${DIAG_D}/
+
+    # Moving all figures to HTML_DIR:
+    for fp in ${FIG_FORM} svg mp4 gif; do mv -f *.${fp} ${HTML_DIR}/ >/dev/null 2>/dev/null ; done
+    mv -f ./merid_transport/*.${FIG_FORM} ${HTML_DIR}/ >/dev/null 2>/dev/null
+    mv -f ${DIAG_D}/movies/movie_*.mp4    ${HTML_DIR}/ >/dev/null 2>/dev/null
+    
+    # Sign with logo?
+    #cd ${HTML_DIR}/
+    #list=`\ls *.png`
+    #for ff in ${list}; do
+    #    sign_image ${ff} n_${ff}
+    #    mv -f n_${ff} ${ff}
+    #done
+    
+    cd ${DIAG_D}/
+
+    . ${BARAKUDA_ROOT}/src/bash/build_html.bash
+
+    wait
+
+    # Building main index.html 
+    build_index_html
+    
+    # If climatology built, sub 2D html pages
+    if ${l_pclim}; then
+        build_sub_html
+    fi
+    
+    #==================================================================
+    
+
+    wait ; # likely waiting for the creation of the GIFs....
+
+    echo; echo
+
+    cp ${BARAKUDA_ROOT}/src/html/conf_*.html ${HTML_DIR}/
+    
+    if [ ${ece_exp} -eq 0 ]; then
+        cp -L ${BARAKUDA_ROOT}/src/html/logo.*g      ${HTML_DIR}/
+    else
+        cp -L ${BARAKUDA_ROOT}/src/html/logo_ece.svg ${HTML_DIR}/logo.svg
+        cp -L ${BARAKUDA_ROOT}/src/html/logo_ece.png ${HTML_DIR}/logo.png
+    fi
+    
+    mv -f index.html namelist*.html ${HTML_DIR}/
+
+    cp -r ${DIRS_2_EXP} ${HTML_DIR}/ >/dev/null 2>/dev/null
+
+    echo; echo; echo
+
+    if [ ${ihttp} -eq 1 ]; then
+        echo "Preparing to export to remote host!"; echo
+        send_dir=`basename ${HTML_DIR}`
+        tar cvf ${send_dir}.tar ${send_dir}
+        ssh ${RUSER}@${RHOST} "mkdir -p ${RWWWD}"
+        scp ${send_dir}.tar ${RUSER}@${RHOST}:${RWWWD}/
+        ssh ${RUSER}@${RHOST} "cd ${RWWWD}/; rm -rf ${send_dir}; tar xf ${send_dir}.tar 2>/dev/null; rm -f ${send_dir}.tar; \
+                               chmod -R a+r ${send_dir}; cd ${send_dir}/"
+        echo; echo
+        echo "Diagnostic page installed on  http://${RHOST}${RWWWD}/${send_dir}/ !"
+        echo "( Also browsable on local host in ${DIAG_D}/${send_dir} )"
+        rm -f ${send_dir}.tar
+
+    else
+        if [ ${ihttp} -eq 0 ]; then
+            echo "Diagnostic page installed in ${HTML_DIR}/"
+            echo " => you can view it with a web browser..."
+        else
+            echo "Error: \"ihttp\" must be either 0 or 1 !"
+        fi
+    fi
+
+    echo; echo
+
+    rm -rf *.eps
+
+
+else
+    echo
+    echo "Diagnostics built and saved! (${DIAG_D})"
+    echo "Re-Run \"${script}.sh\" adding the  \"-e\" or \"-E\" switch to create figure and HTML page..."
+    echo
+fi
+
+rm -rf ${TMP_DIR} 2>/dev/null ; #debug
+
+echo

+ 396 - 0
build_clim.sh

@@ -0,0 +1,396 @@
+#!/usr/bin/env bash
+
+#==============================================================
+#
+#                    B A R A K U D A
+#
+#    An OCEAN MONITORING python environment for NEMO
+#
+#             L. Brodeau, 2009-2017
+#
+#===============================================================
+
+ivt=1   ; # Create a climatology for VT
+iamoc=1 ; # Create a climatology for 2D lat-depth AMOC?
+ibpsi=1 ; # Create a climatology for barotropic stream function
+icurl=1 ; # Create a climatology of the windstress curl
+
+export script=build_clim
+[ -z ${BARAKUDA_ROOT+x} ] && export BARAKUDA_ROOT=${PWD}
+
+# Display available configs:
+list_conf="`\ls ${BARAKUDA_ROOT}/configs/config_*.sh | sed -e "s|${BARAKUDA_ROOT}/configs\/config_||g" -e s/'.sh'/''/g`"
+# User configs, potentially in the directory from which barakuda.sh is called:
+list_conf+=" `\ls ./config_*.sh 2>/dev/null | sed -e "s|.\/config_||g" -e s/'.sh'/''/g`"
+
+
+# Important bash functions:
+. ${BARAKUDA_ROOT}/src/bash/bash_functions.bash
+
+barakuda_init
+
+while getopts R:f:i:e:C:h option ; do
+    case $option in
+        R) export EXP=${OPTARG};;
+        f) export IFREQ_SAV_YEARS=${OPTARG} ;;
+        i) export Y1=${OPTARG} ;;
+        e) export Y2=${OPTARG} ;;
+        C) export CONFIG=${OPTARG};;
+        h)  build_clim_usage ; exit ;;
+        \?) build_clim_usage ; exit ;;
+    esac
+done
+
+barakuda_check
+
+if [ -f ./config_${CONFIG}.sh ]; then
+    # sourcing local configuration file if present:
+    fconfig=./config_${CONFIG}.sh
+else
+    # sourcing barakuda-distribution configuration file:
+    fconfig=${BARAKUDA_ROOT}/configs/config_${CONFIG}.sh
+fi
+if [ -f ${fconfig} ]; then
+    echo "Sourcing configuration file: ${fconfig} !"
+    . ${fconfig}
+else
+    echo "PROBLEM: cannot find file ${fconfig} !"; exit
+fi
+echo
+
+# If auto-submit experiment (ece_exp=10) then overides a few functions with:
+if [ ${ece_exp} -ge 10 ]; then
+    . ${BARAKUDA_ROOT}/src/bash/bash_functions_autosub.bash
+fi
+
+# If 3D fieds are annual averaged then overides a few functions with:
+if [ ! "${ANNUAL_3D}" = "" ]; then
+    . ${BARAKUDA_ROOT}/src/bash/bash_functions_1y.bash
+fi
+
+barakuda_setup
+
+CPRMN="${CPREF}"
+CPRAN=""
+if [ ! "${ANNUAL_3D}" = "" ]; then
+    CPRAN=`echo ${CPREF} | sed -e s/"_${TSTAMP}_"/"_${ANNUAL_3D}_"/g`
+fi
+
+echo
+echo " SETTINGS: "
+echo "   *** DIAG_D   = ${DIAG_D} "
+echo "   *** CLIM_DIR = ${CLIM_DIR} "
+echo "   *** TMP_DIR  = ${TMP_DIR} "
+echo "   *** Y1       = ${Y1} "
+echo "   *** Y2       = ${Y2} "
+echo "   *** CONFIG   = ${CONFIG} "
+echo "   *** GRID     = ${ORCA} "
+echo "   *** CONFEXP  = ${CONFEXP} "
+echo "   *** EXP      = ${EXP} "
+echo "   *** CPREF    = ${CPREF} "
+echo "   *** Monthly files prefix = ${CPRMN} (${NEMO_SAVED_FILES})"
+if [ ! "${CPRAN}" = "" ]; then
+    echo "   ***  Annual files prefix = ${CPRAN} (${NEMO_SAVED_FILES_3D})"
+fi
+echo "   *** IFREQ_SAV_YEARS = ${IFREQ_SAV_YEARS} "
+echo "   *** NCDF_DIR        = ${NCDF_DIR} "
+echo
+
+mkdir -p ${DIAG_D}
+barakuda_first_last_years ; # look at NEMO files to know what are first and last years available...
+echo ${IFREQ_SAV_YEARS} > ${DIAG_D}/numb_year_per_file.info
+echo ${YEAR_INI}        > ${DIAG_D}/first_year.info
+
+# How to convert from nc3 to nc4?
+wc=`which nccopy`
+if [ "${wc}" = "" ]; then
+    CP2NC4="${NCDF_DIR}/bin/nccopy -k 4 -d 9"
+else
+    CP2NC4="nccopy -k 4 -d 9"
+fi
+wc=`which nc3tonc4` ; # Comes with Canopy...
+if [ ! "${wc}" = "" ]; then
+    CP2NC4="nc3tonc4"
+fi
+
+
+export PATH=${BARAKUDA_ROOT}/cdftools_light/bin:${PYTHON_HOME}/bin:${PATH}
+
+Y1=$((${Y1}+0))
+Y2=$((${Y2}+0))
+CY1=`printf "%04d" ${Y1}`
+CY2=`printf "%04d" ${Y2}`
+
+mkdir -p ${CLIM_DIR}
+
+
+# Variables to extract:
+V2E="${NN_SST},${NN_SSS},${NN_SSH},${NN_T},${NN_S},${NN_MLD}"
+C2ET="nav_lon,nav_lat,deptht"
+C2EU="nav_lon,nav_lat,depthu"
+C2EV="nav_lon,nav_lat,depthv"
+C2EW="nav_lon,nav_lat,depthw"
+
+GRID_IMP="grid_T"
+if [ ${ivt} -eq 1 ] || [ ${ibpsi} -eq 1 ] || [ ${icurl} -eq 1 ]; then
+    GRID_IMP+=" grid_U"
+fi
+if [ ${iamoc} -eq 1 ] || [ ${ivt} -eq 1 ] || [ ${ibpsi} -eq 1 ] || [ ${icurl} -eq 1 ]; then
+    GRID_IMP+=" grid_V"
+fi
+if [ `contains_string ${FILE_ICE_SUFFIX} ${NEMO_SAVED_FILES}` -eq 1 ]; then
+    GRID_IMP+=" ${FILE_ICE_SUFFIX}"
+fi
+if [ `contains_string SBC ${NEMO_SAVED_FILES}` -eq 1 ]; then
+    GRID_IMP+=" SBC"
+fi
+echo; echo " GRID_IMP = ${GRID_IMP}"; echo
+
+
+# Checking what files we have / plan to use:
+if [ -z "${NEMO_SAVED_FILES}" ]; then
+    echo "Please specify which NEMO files are saved (file suffixes, grid_T, ..., icemod) ?"
+    echo " => set the variable NEMO_SAVED_FILES in your config_${CONFIG}.sh file!"; exit
+fi
+VAF=( "grid_T" "grid_U" "grid_V" "icemod" "SBC" )
+js=0 ; gimp_new=""
+for sf in ${VAF[*]}; do
+    echo "Checking ${sf}..."
+    ca=`echo "${NEMO_SAVED_FILES} ${NEMO_SAVED_FILES_3D}" | grep ${sf}`
+    cb=`echo "${GRID_IMP}"         | grep ${sf}`
+    if [ "${ca}" = "" ]; then
+        if [ "${cb}" != "" ]; then
+            echo "PROBLEM! The diags you specified say you need ${sf} files"
+            echo "     => but you have not specified ${sf} in NEMO_SAVED_FILES !"; exit
+        fi
+    else
+        gimp_new="${sf} ${gimp_new}"
+    fi
+    ((js++))
+done
+GRID_IMP=${gimp_new}
+echo; echo "File types to import: ${GRID_IMP}"; echo; echo
+
+
+VCM=( "01" "02" "03" "04" "05" "06" "07" "08" "09" "10" "11" "12" )
+
+cd ${TMP_DIR}/
+
+echo; echo "In:"; pwd
+
+barakuda_import_mesh_mask
+
+ls -l ; echo; echo
+
+
+nby=$((${Y2}-${Y1}+1))
+
+if [ ! $((${nby}%${IFREQ_SAV_YEARS})) -eq 0 ]; then
+    echo " Number of years should be a multiple of ${IFREQ_SAV_YEARS}!"; exit
+fi
+
+if [ ${ece_exp} -gt 0 ] && [ ${ece_exp} -lt 10 ] ; then
+    if [ ! -d ${NEMO_OUT_D}/001 ]; then echo "ERROR: since ece_exp=${ece_exp}, there should be a directory 001 in:"; echo " ${NEMO_OUT_D}"; fi
+fi
+
+ffirsty="${DIAG_D}/first_year.info"
+if [ ! -f  ${ffirsty} ]; then echo "ERROR: file ${ffirsty} not found!!!"; exit; fi
+export YEAR_INI_F=`cat ${ffirsty}`
+export jyear=${Y1}
+
+
+while [ ${jyear} -le ${Y2} ]; do
+
+    export cyear=`printf "%04d" ${jyear}` ; echo ; echo "Year = ${cyear}"
+
+    cpf=""
+    if [ ${ece_exp} -gt 0 ]; then
+        iy=$((${jyear}-${Y1}+1+${Y1}-${YEAR_INI_F}))
+        dir_ece=`printf "%03d" ${iy}`
+        echo " *** ${cyear} => dir_ece = ${dir_ece}"
+        cpf="${dir_ece}/"
+    fi
+
+    i_get_file=0
+    if [ $((${jyear}%${IFREQ_SAV_YEARS})) -eq 0 ]; then
+        barakuda_check_year_is_complete  ; # lcontinue might be updated to false!
+    fi
+
+    CRT1M=${CPRMN}${cyear}${cmmdd1}_${cyear}${cmmdd2}
+
+    barakuda_import_files
+
+    # Monthly files to work with for current year:
+    ft1m=${CRT1M}_grid_T.nc
+    fu1m=${CRT1M}_grid_U.nc
+    fv1m=${CRT1M}_grid_V.nc
+    # Annual files to work with for current year:
+    CRT1Y=`echo ${CRT1M} | sed -e s/"_${TSTAMP}_"/"_${ANNUAL_3D}_"/g`
+    ft1y=${CRT1Y}_grid_T.nc
+    fu1y=${CRT1Y}_grid_U.nc
+    fv1y=${CRT1Y}_grid_V.nc
+    fj1y=${CRT1Y}_${FILE_ICE_SUFFIX}.nc ; # can be icemod or grid_T ....
+    CFG3D=${CRT1M}
+    CPREF3D=${CPRMN}
+    #
+    # Files that contain the 3D fields (might be monthly or annaual sometimes (when "${ANNUAL_3D}" = "1y")    $
+    ft3d=${ft1m}
+    fu3d=${fu1m}
+    fv3d=${fv1m}
+    if [ "${ANNUAL_3D}" = "1y" ]; then
+        [[ ${NEMO_SAVED_FILES_3D} =~ (^|[[:space:]])"grid_U"($|[[:space:]]) ]] \
+            && CPREF3D=${CPRAN}; CFG3D=${CRT1Y}; ft3d=${ft1y}; fu3d=${fu1y}; fv3d=${fv1y} \
+            || echo "...default"
+        echo ""
+    fi
+    fvt=${CFG3D}_VT.nc
+
+    echo
+
+    if [ ${ivt} -eq 1 ]; then
+        # Creating VT files:
+        echo " *** CALLING: cdfvT.x ${CFG3D} ${NN_T} ${NN_S} ${NN_U} ${NN_V} ${NN_U_EIV} ${NN_V_EIV} &"
+        cdfvT.x ${CFG3D} ${NN_T} ${NN_S} ${NN_U} ${NN_V} ${NN_U_EIV} ${NN_V_EIV} &
+        echo
+    fi
+
+    echo
+
+    if [ ${iamoc} -eq 1 ]; then
+        rm -f moc.nc
+        echo " *** CALLING: cdfmoc.x ${fv3d} ${NN_V} ${NN_V_EIV} &"
+        cdfmoc.x ${fv3d} ${NN_V} ${NN_V_EIV} &
+        echo
+    fi
+
+    if [ ${ibpsi} -eq 1 ]; then
+        rm -f psi.nc
+        echo " *** CALLING: cdfpsi.x ${fu3d} ${fv3d} ${NN_U} ${NN_V} &"
+        cdfpsi.x ${fu3d} ${fv3d} ${NN_U} ${NN_V} &
+        echo
+    fi
+
+    if [ ${icurl} -eq 1 ]; then
+        # Curl of wind stress
+        if [ ! "${NN_TAUX}" = "X" ] && [ ! "${NN_TAUY}" = "X" ]; then
+            rm -f curl.nc
+            echo " *** CALLING: cdfcurl.x ${fu3d} ${fv3d} ${NN_TAUX} ${NN_TAUY} 1 &"
+            cdfcurl.x ${fu3d} ${fv3d} ${NN_TAUX} ${NN_TAUY} 1 &
+        else
+            echo " You need to define NN_TAUX and NN_TAUY if you want to compute the curl of the wind stress!"
+        fi
+        echo
+    fi
+
+    wait
+
+    ncwa -O -a x moc.nc ${CFG3D}_MOC.nc ; # removing degenerate x record...
+    rm -f moc.nc
+
+    if [ ${ibpsi} -eq 1 ]; then mv -f psi.nc  ${CFG3D}_PSI.nc;   fi
+    if [ ${icurl} -eq 1 ]; then mv -f curl.nc ${CFG3D}_TCURL.nc; fi
+
+    echo "After year ${jyear}:"; ls -l *.nc*
+    echo
+
+    ((jyear++))
+    export jyear=${jyear}
+
+done
+
+echo
+echo "Phase 2:"; ls ; echo
+
+
+# Mean monthly climatology
+
+SUFF_FOR_MONTHLY="${NEMO_SAVED_FILES}"
+if [ "${ANNUAL_3D}" = "" ]; then SUFF_FOR_MONTHLY+=" VT MOC PSI TCURL"; fi
+echo; echo "Will build monthly clim for files with these suffixes:"; echo ${SUFF_FOR_MONTHLY}; echo
+
+for suff in ${SUFF_FOR_MONTHLY}; do
+    if [ -f ./${CRT1M}_${suff}.nc ]; then
+        echo ; echo " Treating ${suff} files!"; echo
+        f2c=mclim_${CONFEXP}_${CY1}-${CY2}_${suff}.nc
+        rm -f ${CLIM_DIR}/${f2c}*
+        echo
+        jm=0
+        for cm in ${VCM[*]}; do
+            ((jm++))
+            if [ -f ./${CRT1M}_${suff}.nc ]; then
+                echo; ls ; echo
+                echo "ncra -F -O -d time_counter,${jm},,12 ${CPRMN}*${cmmdd1}_*${cmmdd2}_${suff}.nc -o mean_m${cm}_${suff}.nc"
+                ncra -F -O -d time_counter,${jm},,12 ${CPRMN}*${cmmdd1}_*${cmmdd2}_${suff}.nc -o mean_m${cm}_${suff}.nc &
+                echo
+            fi
+        done
+        wait
+
+        echo; ls ; echo
+        echo "ncrcat -O  mean_m*_${suff}.nc out_${suff}.nc"
+        ncrcat -O  mean_m*_${suff}.nc out_${suff}.nc
+        rm mean_m*_${suff}.nc
+        echo
+        echo "mv -f out_${suff}.nc ${f2c}"
+        mv -f out_${suff}.nc ${f2c}
+        echo
+    else
+        echo ; echo " Ignoring monthly ${suff} files!"; echo
+    fi
+
+done ; # loop along monthly files suffixes
+
+wait
+
+
+# Mean annual climatology for 3D-variable-based fields:
+
+SUFF_FOR_ANNUAL="VT MOC PSI TCURL"
+if [ ! "${ANNUAL_3D}" = "" ]; then SUFF_FOR_ANNUAL+=" ${NEMO_SAVED_FILES_3D}"; fi
+echo; echo "Will build annual clim for files with these suffixes:"; echo ${SUFF_FOR_ANNUAL}; echo
+
+for suff in ${SUFF_FOR_ANNUAL}; do
+    if [ -f ./${CRT1Y}_${suff}.nc ] || [ -f ./${CRT1M}_${suff}.nc ]; then
+        echo ; echo " Treating ${suff} files!"; echo
+        f2c=aclim_${CONFEXP}_${CY1}-${CY2}_${suff}.nc
+        rm -f ${CLIM_DIR}/${f2c}*
+        #
+        echo "ncra -O ${CPREF3D}*_${suff}.nc -o ${f2c} &"
+        ncra -O ${CPREF3D}*_${suff}.nc -o ${f2c} &
+        echo
+    else
+        echo ; echo " Ignoring annual ${suff} files!"; echo
+    fi
+done ; # loop along annual files suffixes
+wait
+
+rm -f ${CPRMN}*${cmmdd1}_*${cmmdd2}_*.nc ${CPRAN}*${cmmdd1}_*${cmmdd2}_*.nc
+
+
+
+list=`\ls [am]clim_${CONFEXP}*.nc`
+for ff in ${list}; do
+    fn=`echo ${ff} | sed -e s/'.nc'/'.nc4'/g`
+    echo "${CP2NC4}  ${ff} ${fn} &"
+    ${CP2NC4}  ${ff} ${fn} &
+    echo
+done
+
+wait
+
+for cl in aclim mclim; do
+    echo "mv -f ${cl}_${CONFEXP}*.nc4 ${CLIM_DIR}/"
+    mv -f ${cl}_${CONFEXP}*.nc4 ${CLIM_DIR}/
+    echo
+done
+
+
+echo;echo
+echo "${CY1}-${CY2}" > ${CLIM_DIR}/last_clim
+echo "Climatology saved into: ${CLIM_DIR}/"
+echo;echo
+
+cd /tmp/
+rm -rf ${TMP_DIR} 2>/dev/null
+
+exit 0

+ 162 - 0
cdftools_light/Makefile

@@ -0,0 +1,162 @@
+# Makefile for CDFTOOLS 
+
+# ( make.macro is a link that points to the file macro.xxx where 
+#   xxx is representative of your machine )
+# !!  $Rev: 324 $
+# !!  $Date: 2010-05-21 18:46:16 +0200 (Fri, 21 May 2010) $
+# !!  $Id: Makefile 324 2010-05-21 16:46:16Z molines $
+# !!--------------------------------------------------------------
+
+
+include make.macro
+
+
+CDFTOOLS=CDFTOOLS-2.1
+
+
+
+EXEC = ./bin/cdfpsi.x \
+       ./bin/cdfmaxmoc.x \
+       ./bin/cdfmhst.x \
+       ./bin/cdfsigtrp.x \
+       ./bin/cdficediags.x \
+       ./bin/cdfmoc.x \
+       ./bin/cdfcurl.x \
+       ./bin/cdfvT.x \
+       ./bin/cdftransportiz.x \
+       ./bin/cdftransport_test_sign.x \
+       ./bin/cdficeflux.x
+
+all: $(EXEC)
+
+## Statistical programs
+./bin/cdfmoy.x: src/cdfio.o   src/cdfmoy.f90
+	$(F90) src/cdfmoy.f90 -o ./bin/cdfmoy.x  src/cdfio.o  $(FFLAGS)
+
+./bin/cdfpsi.x: src/cdfio.o src/io_ezcdf.o src/cdfpsi.f90
+	$(F90) src/cdfpsi.f90 -o ./bin/cdfpsi.x  src/cdfio.o src/io_ezcdf.o $(FFLAGS)
+
+./bin/cdfeke.x: src/cdfio.o  src/cdfeke.f90
+	$(F90) src/cdfeke.f90 -o ./bin/cdfeke.x  src/cdfio.o $(FFLAGS)
+
+./bin/cdfrmsssh.x: src/cdfio.o  src/cdfrmsssh.f90
+	$(F90) src/cdfrmsssh.f90 -o ./bin/cdfrmsssh.x  src/cdfio.o $(FFLAGS)
+
+./bin/cdfvT.x: src/cdfio.o  src/io_ezcdf.o src/cdfvT.f90
+	$(F90) src/cdfvT.f90 -o ./bin/cdfvT.x  src/cdfio.o src/io_ezcdf.o $(FFLAGS)
+
+./bin/cdfcurl.x: src/cdfio.o  src/cdfcurl.f90
+	$(F90) src/cdfcurl.f90 -o ./bin/cdfcurl.x  src/cdfio.o $(FFLAGS)
+
+./bin/cdfmhst.x: src/cdfio.o  src/cdfmhst.f90
+	$(F90) src/cdfmhst.f90 -o ./bin/cdfmhst.x  src/cdfio.o $(FFLAGS)
+
+./bin/cdfmxl.x: src/cdfio.o src/eos.o  src/cdfmxl.f90
+	$(F90) src/cdfmxl.f90 -o ./bin/cdfmxl.x  src/cdfio.o src/eos.o $(FFLAGS)
+
+./bin/cdftransportiz.x: src/cdfio.o src/io_ezcdf.o src/cdftransportiz.f90
+	$(F90) src/cdftransportiz.f90 -o ./bin/cdftransportiz.x  src/cdfio.o src/io_ezcdf.o $(FFLAGS)
+
+./bin/cdftransport_test_sign.x: src/cdfio.o src/io_ezcdf.o src/cdftransport_test_sign.f90
+	$(F90) src/cdftransport_test_sign.f90 -o ./bin/cdftransport_test_sign.x  src/cdfio.o src/io_ezcdf.o $(FFLAGS)
+
+./bin/cdficeflux.x: src/cdfio.o src/io_ezcdf.o src/cdficeflux.f90
+	$(F90) src/cdficeflux.f90 -o ./bin/cdficeflux.x  src/cdfio.o $(FFLAGS)
+
+./bin/cdfsigtrp.x: src/cdfio.o src/io_ezcdf.o src/eos.o  src/cdfsigtrp.f90
+	$(F90)  src/cdfsigtrp.f90 -o ./bin/cdfsigtrp.x  src/cdfio.o src/io_ezcdf.o src/eos.o $(FFLAGS)
+
+./bin/cdfmoc.x: src/cdfio.o src/io_ezcdf.o src/cdfmoc.f90
+	$(F90) src/cdfmoc.f90 -o ./bin/cdfmoc.x  src/cdfio.o src/io_ezcdf.o $(FFLAGS)
+
+./bin/cdfmocsig.x: src/cdfio.o src/eos.o  src/cdfmocsig.f90
+	$(F90) src/cdfmocsig.f90 -o ./bin/cdfmocsig.x  src/cdfio.o src/eos.o $(FFLAGS)
+
+./bin/cdfmocatl.x: src/cdfio.o  src/cdfmocatl.f90
+	$(F90) src/cdfmocatl.f90 -o ./bin/cdfmocatl.x  src/cdfio.o $(FFLAGS)
+
+./bin/cdfmean.x: src/cdfio.o  src/cdfmean.f90
+	$(F90) src/cdfmean.f90 -o ./bin/cdfmean.x  src/cdfio.o $(FFLAGS)
+
+./bin/cdfmeanvar.x: src/cdfio.o  src/cdfmeanvar.f90
+	$(F90) src/cdfmeanvar.f90 -o ./bin/cdfmeanvar.x  src/cdfio.o $(FFLAGS)
+
+./bin/cdfheatc.x: src/cdfio.o  src/cdfheatc.f90
+	$(F90) src/cdfheatc.f90 -o ./bin/cdfheatc.x  src/cdfio.o $(FFLAGS)
+
+./bin/cdfmxlheatc.x: src/cdfio.o  src/cdfmxlheatc.f90
+	$(F90) src/cdfmxlheatc.f90 -o ./bin/cdfmxlheatc.x  src/cdfio.o $(FFLAGS)
+
+./bin/cdficediags.x: src/cdfio.o  src/cdficediags.f90
+	$(F90) src/cdficediags.f90 -o ./bin/cdficediags.x  src/cdfio.o $(FFLAGS)
+
+./bin/cdfzonalmean.x: src/cdfio.o  src/cdfzonalmean.f90
+	$(F90) src/cdfzonalmean.f90 -o ./bin/cdfzonalmean.x  src/cdfio.o $(FFLAGS) 
+
+./bin/cdfzonalsum.x: src/cdfio.o  src/cdfzonalsum.f90
+	$(F90) src/cdfzonalsum.f90 -o ./bin/cdfzonalsum.x  src/cdfio.o $(FFLAGS) 
+
+./bin/cdfzonalout.x: src/cdfio.o  src/cdfzonalout.f90
+	$(F90) src/cdfzonalout.f90 -o ./bin/cdfzonalout.x  src/cdfio.o $(FFLAGS) 
+
+./bin/cdfhflx.x: src/cdfio.o  src/cdfhflx.f90
+	$(F90) src/cdfhflx.f90 -o ./bin/cdfhflx.x  src/cdfio.o $(FFLAGS)
+
+./bin/cdfbuoyflx: src/cdfio.o  src/eos.o cdfbuoyflx.f90
+	$(F90) src/cdfbuoyflx.f90 -o ./bin/cdfbuoyflx.x  src/cdfio.o src/eos.o $(FFLAGS)
+
+./bin/cdfmaxmoc.x: src/cdfio.o src/io_ezcdf.o src/cdfmaxmoc.f90
+	$(F90) src/cdfmaxmoc.f90 -o ./bin/cdfmaxmoc.x  src/cdfio.o src/io_ezcdf.o $(FFLAGS)
+
+./bin/cdfw.x: src/cdfio.o  src/cdfw.f90
+	$(F90) src/cdfw.f90 -o ./bin/cdfw.x  src/cdfio.o $(FFLAGS)
+
+
+## Modules
+
+src/cdfio.o: src/cdfio.f90
+	@mkdir -p mod
+	@mkdir -p bin
+	$(F90) -c src/cdfio.f90 $(FFLAGS) -o src/cdfio.o
+
+
+src/io_ezcdf.o: src/io_ezcdf.f90
+	@mkdir -p mod
+	@mkdir -p bin
+	$(F90) -c src/io_ezcdf.f90 $(FFLAGS) -o src/io_ezcdf.o
+
+
+
+#src/modcdfnames.o: src/modcdfnames.f90
+#	@mkdir -p mod
+#	$(F90) -c src/modcdfnames.f90 $(FFLAGS) -o src/modcdfnames.o
+
+src/eos.o: src/eos.f90
+	@mkdir -p mod
+	@mkdir -p bin
+	$(F90) -c src/eos.f90   $(FFLAGS) -o src/eos.o
+
+cdftools.o: src/cdfio.o cdftools.f90
+	@mkdir -p mod
+	@mkdir -p bin
+	$(F90) -c cdftools.f90 $(FFLAGS)
+
+modpoly.o: modpoly.f90
+	@mkdir -p mod
+	$(F90) -c modpoly.f90 $(FFLAGS)
+
+## Utilities
+tar:
+	( cd ../ ; tar cf cdftools-2.1.tar $(CDFTOOLS)/*90 $(CDFTOOLS)/Make* \
+          $(CDFTOOLS)/section.dat $(CDFTOOLS)/JOBS $(CDFTOOLS)/DOC \
+          $(CDFTOOLS)/macro.* )
+
+clean:
+	\rm -rf mod src/*.o  *~ bin
+
+cleanexe: clean
+	\rm -f $(EXEC)
+
+#install:
+#	\mv -f $(EXEC) ../bin/
+#

+ 17 - 0
cdftools_light/macro/macro.gfortran_ekman

@@ -0,0 +1,17 @@
+# Makefile for CDFTOOLS
+#    $Rev: 173 $
+#    $Date: 2008-03-17 11:42:21 +0100 (Mon, 17 Mar 2008) $
+# --------------------------------------------------------------
+
+NCDF_DIR=/afs/pdc.kth.se/home/b/brodeau/Public/opt/netcdf_gcc
+
+NCDF= -I$(NCDF_DIR)/include -L$(NCDF_DIR)/lib -lnetcdf
+
+F90=gfortran
+
+# -fdefault-real-8 -fbounds-check
+
+FFLAGS= -O2 -I./mod -J./mod $(NCDF)
+
+#INSTALL=../bin/
+

+ 17 - 0
cdftools_light/macro/macro.gfortran_gustafson

@@ -0,0 +1,17 @@
+
+# Install 'libnetcdff-dev'
+
+NCDF_DIR=/shared/earth/software/netCDF-Fortran/4.2-foss-2015a
+
+NCDF= -I$(NCDF_DIR)/include -L$(NCDF_DIR)/lib -lnetcdff -lnetcdf
+
+F90=gfortran
+
+# -fdefault-real-8 -fbounds-check
+
+#FFLAGS= -O0  -ffixed-line-length-0 -Wall -Wextra -ffpe-trap=zero,overflow,underflow -fbacktrace -I./mod -J./mod $(NCDF)
+
+FFLAGS= -O2 -ffixed-line-length-0 -ffpe-trap=zero,overflow,underflow -fbacktrace -I./mod -J./mod $(NCDF)
+
+#INSTALL=../bin/
+

+ 15 - 0
cdftools_light/macro/macro.gfortran_ubuntu

@@ -0,0 +1,15 @@
+
+# Install 'libnetcdff-dev'
+
+NCDF_DIR=/usr
+
+NCDF= -I$(NCDF_DIR)/include -L$(NCDF_DIR)/lib -lnetcdff -lnetcdf
+
+F90=gfortran
+
+# -fdefault-real-8 -fbounds-check
+
+FFLAGS= -O2 -I./mod -J./mod $(NCDF)
+
+#INSTALL=../bin/
+

+ 17 - 0
cdftools_light/macro/macro.gfortran_vagn

@@ -0,0 +1,17 @@
+# Makefile for CDFTOOLS
+#    $Rev: 173 $
+#    $Date: 2008-03-17 11:42:21 +0100 (Mon, 17 Mar 2008) $
+# --------------------------------------------------------------
+
+NCDF_DIR=/home/x_laubr/opt/netcdf_gcc
+
+NCDF= -I$(NCDF_DIR)/include -L$(NCDF_DIR)/lib -lnetcdf
+
+F90=gfortran
+
+# -fdefault-real-8 -fbounds-check
+
+FFLAGS= -O2 -I./mod -J./mod $(NCDF)
+
+#INSTALL=../bin/
+

+ 9 - 0
cdftools_light/macro/macro.gfortran_zenobe

@@ -0,0 +1,9 @@
+NCDF_DIR=/projects/acad/ecearth/opt/software/netCDF/4.4.1-foss-2016b
+NCDFF_DIR=/projects/acad/ecearth/opt/software/netCDF-Fortran/4.4.4-foss-2016b
+
+NCDF=-I$(NCDFF_DIR)/include -L$(NCDFF_DIR)/lib -lnetcdff
+
+F90=gfortran
+
+FFLAGS= -O2 -I./mod  $(NCDF) 
+

+ 13 - 0
cdftools_light/macro/macro.ifort

@@ -0,0 +1,13 @@
+# Makefile for CDFTOOLS
+# --------------------------------------------------------------
+
+NCDF_DIR=/opt/netcdf_intel11
+
+NCDF= -I$(NCDF_DIR)/include -L$(NCDF_DIR)/lib -lnetcdf
+
+# -lnetcdff
+
+F90=ifort
+
+FFLAGS= -O3 -module ./mod $(NCDF)
+

+ 25 - 0
cdftools_light/macro/macro.ifort_beskow

@@ -0,0 +1,25 @@
+# Makefile for CDFTOOLS
+#    $Rev: 173 $
+#    $Date: 2008-03-17 11:42:21 +0100 (Mon, 17 Mar 2008) $
+# --------------------------------------------------------------
+
+#NCDF_DIR=/home/x_laubr/Public/netcdf-4.3.0_intel1214_par
+
+NCDF_DIR = /opt/cray/netcdf-hdf5parallel/4.3.2/intel/140
+
+NCDF= -I$(NCDF_DIR)/include -L$(NCDF_DIR)/lib -lnetcdf -lnetcdff
+
+F90=ifort
+
+
+# -fdefault-real-8 -fbounds-check
+
+##FFLAGS= -O3 -parallel -module ./mod $(NCDF)
+##FFLAGS= -O3 -parallel -xHost -module ./mod $(NCDF)
+
+
+FFLAGS= -O3 -module ./mod $(NCDF)
+
+#FFLAGS= -O0 -CB -traceback -module ./mod $(NCDF)
+
+

+ 23 - 0
cdftools_light/macro/macro.ifort_bi

@@ -0,0 +1,23 @@
+# Makefile for CDFTOOLS
+#    $Rev: 173 $
+#    $Date: 2008-03-17 11:42:21 +0100 (Mon, 17 Mar 2008) $
+# --------------------------------------------------------------
+
+NCDF_DIR = /software/apps/netcdf/4.3.2/i1501-hdf5-1.8.14
+
+NCDF= -I$(NCDF_DIR)/include -L$(NCDF_DIR)/lib -lnetcdf -lnetcdff
+
+F90 = ifort
+
+
+# -fdefault-real-8 -fbounds-check
+
+##FFLAGS= -O3 -parallel -module ./mod $(NCDF)
+##FFLAGS= -O3 -parallel -xHost -module ./mod $(NCDF)
+
+
+FFLAGS= -O3 -xHOST -module ./mod $(NCDF)
+
+#FFLAGS= -O0 -CB -traceback -module ./mod $(NCDF)
+
+

+ 11 - 0
cdftools_light/macro/macro.ifort_cca

@@ -0,0 +1,11 @@
+# Makefile for CDFTOOLS
+# --------------------------------------------------------------
+
+NCDF_DIR=/opt/cray/netcdf-hdf5parallel/4.4.0/intel/150
+
+NCDF= -I$(NCDF_DIR)/include -L$(NCDF_DIR)/lib -lnetcdf -lnetcdff
+
+F90=ifort
+
+FFLAGS= -O3 -module ./mod $(NCDF)
+

+ 18 - 0
cdftools_light/macro/macro.ifort_marenostrum

@@ -0,0 +1,18 @@
+NCDF_DIR=/apps/NETCDF/4.1.3
+
+NCDF=-I$(NCDF_DIR)/include -L$(NCDF_DIR)/lib -lnetcdf -lnetcdff
+
+F90=ifort
+
+
+# -fdefault-real-8 -fbounds-check
+
+##FFLAGS= -O3 -parallel -module ./mod $(NCDF)
+##FFLAGS= -O3 -parallel -xHost -module ./mod $(NCDF)
+
+
+FFLAGS= -O3 -xHOST -module ./mod $(NCDF)
+
+#FFLAGS= -O0 -CB -traceback -module ./mod $(NCDF)
+
+

+ 12 - 0
cdftools_light/macro/macro.ifort_rhino

@@ -0,0 +1,12 @@
+# Makefile for CDFTOOLS
+# --------------------------------------------------------------
+
+NCDF_DIR=/nfs/home/users/severijn/
+
+NCDF= -I$(NCDF_DIR)/include -L$(NCDF_DIR)/lib -lnetcdf -lnetcdff
+
+F90=ifort
+
+#FFLAGS= -O3 -module ./mod $(NCDF)
+FFLAGS= -O0 -fpe0 -CB -traceback -module ./mod $(NCDF)
+

+ 8 - 0
cdftools_light/macro/macro.ifort_triolith

@@ -0,0 +1,8 @@
+
+NCDF_DIR = /software/apps/netcdf/4.3.2/i1214-hdf5-1.8.12-AVX-off
+
+NCDF= -I$(NCDF_DIR)/include -L$(NCDF_DIR)/lib -lnetcdf -lnetcdff
+
+F90=ifort
+
+FFLAGS= -O3 -xHOST -CB -traceback -fpe0  -module ./mod $(NCDF)

+ 179 - 0
cdftools_light/src/cdfcurl.f90

@@ -0,0 +1,179 @@
+PROGRAM cdfcurl
+   !!---------------------------------------------------------------------------
+   !!         ***  PROGRAM  cdfcurl  ***
+   !!
+   !!  **  Purpose: Compute the curl on F-points for given gridU gridV files and variables
+   !!
+   !! history :
+   !!   Original :  J.M. Molines (May 2005)
+   !!---------------------------------------------------------------------
+   !!  $Rev: 256 $
+   !!  $Date: 2009-07-21 17:49:27 +0200 (Tue, 21 Jul 2009) $
+   !!  $Id: cdfcurl.f90 256 2009-07-21 15:49:27Z molines $
+   !!--------------------------------------------------------------
+   !! * Modules used
+   USE cdfio
+
+   !! * Local variables
+   IMPLICIT NONE
+   INTEGER :: ji,jj,jk, jt, ilev, istatus
+   INTEGER :: npiglo, npjglo, npk, nt
+   INTEGER :: narg, iargc, ncout, ierr
+   INTEGER, DIMENSION(2) ::  ipk, id_varout         !lolo
+
+   REAL(kind=8), DIMENSION(:,:), ALLOCATABLE  :: e2v, e1u, e1f, e2f
+   REAL(kind=4), DIMENSION(:,:), ALLOCATABLE  :: un_t, vn_t, rotn, taum, tmask, fmask, zun, zvn
+   REAL(KIND=4) ,DIMENSION(:), ALLOCATABLE    ::  tim
+
+   CHARACTER(LEN=256) :: cfilu, cfilv, cvaru, cvarv, cdum, ctim
+   CHARACTER(LEN=256) :: cf_mm='mesh_mask.nc', cfileout='curl.nc'
+   TYPE (variable), DIMENSION(2) :: typvar         !: structure for attibutes
+
+   !!
+   narg = iargc()
+   IF ( narg /= 5 ) THEN
+      PRINT *,' USAGE : cdfcurl fileU fileV varU varV lev'
+      PRINT *,'        lev is the level where the curl will be computed'
+      PRINT *,'        Produce a cdf file curl.nc with socurl variable'
+      PRINT *,'        Needs mesh_mask.nc'
+      PRINT *,'                          '
+      STOP
+   ENDIF
+
+   CALL getarg(1, cfilu)
+   CALL getarg(2, cfilv)
+   CALL getarg(3, cvaru)
+   CALL getarg(4, cvarv)
+   CALL getarg(5, cdum)
+   READ(cdum,*) ilev
+
+   ! define new variables for output ( must update att.txt)
+   typvar(1)%name='socurl'
+   typvar(1)%units='10^-6 s-1'
+   typvar(1)%missing_value=-9999.
+   typvar(1)%valid_min= -1000.
+   typvar(1)%valid_max= 1000.
+   typvar(1)%long_name='Relative_Vorticity (curl)'
+   typvar(1)%short_name='socurl'
+   typvar(1)%online_operation='N/A'
+   typvar(1)%axis='TYX'
+
+   typvar(2)%name='sotaum'
+   typvar(2)%units='N/m^2'
+   typvar(2)%missing_value=-9999.
+   typvar(2)%valid_min= -1000.
+   typvar(2)%valid_max= 1000.
+   typvar(2)%long_name='Wind stress module (on T-point)'
+   typvar(2)%short_name='sotaum'
+   typvar(2)%online_operation='N/A'
+   typvar(2)%axis='TYX'
+
+
+   ipk(:) = 1  !  2D
+
+   npiglo = getdim(cfilu,'x')
+   npjglo = getdim(cfilu,'y')
+   npk    = getdim(cfilu,'depth')
+
+   ctim = 'none'
+   nt    = getdim (cfilu,'time',cdtrue=ctim,kstatus=istatus) !LB
+
+   PRINT *, 'npiglo =',npiglo
+   PRINT *, 'npjglo =',npjglo
+   PRINT *, 'npk    =',npk
+   PRINT *, 'nt     =',nt  !PM
+   PRINT *, 'ilev   =',ilev
+
+   !test if lev exists
+   IF ((npk==0) .AND. (ilev .GT. 0) ) THEN
+      PRINT *, 'Problem : npk = 0 and lev > 0 STOP'
+      STOP
+   END IF
+
+   ! if forcing field (PM)
+   IF (ilev==0 .AND. npk==0) THEN
+      !lforcing=.TRUE.
+      npk = 1 ; ilev=1
+      PRINT *, 'npk =0, assume 1'
+   END IF
+
+   IF (nt==0) THEN
+      PRINT *, 'nt=0, assume 1'
+      nt=1
+   END IF
+   !end (PM)
+
+   ! check files and determines if the curl will be 2D of 3D
+
+   ! create output fileset
+   ncout =create(cfileout, cfilu, npiglo,npjglo,0)
+   ierr= createvar(ncout ,typvar, 2, ipk, id_varout )
+   ierr= putheadervar(ncout, cfilu, npiglo, npjglo, 0)
+
+
+   ! Allocate the memory
+   ALLOCATE ( e1u(npiglo,npjglo) , e1f(npiglo,npjglo) )
+   ALLOCATE ( e2v(npiglo,npjglo) , e2f(npiglo,npjglo) )
+   ALLOCATE ( un_t(npiglo,npjglo)  , vn_t(npiglo,npjglo)  )
+   ALLOCATE ( zun(npiglo,npjglo) , zvn(npiglo,npjglo) )
+   ALLOCATE ( rotn(npiglo,npjglo) , taum(npiglo,npjglo) )
+   ALLOCATE ( tmask(npiglo,npjglo) , fmask(npiglo,npjglo) )
+   ALLOCATE ( tim(nt) )
+
+   e1u=  getvar(cf_mm, 'e1u', 1,npiglo,npjglo)
+   e1f=  getvar(cf_mm, 'e1f', 1,npiglo,npjglo)
+   e2v=  getvar(cf_mm, 'e2v', 1,npiglo,npjglo)
+   e2f=  getvar(cf_mm, 'e2f', 1,npiglo,npjglo)
+   fmask =  getvar(cf_mm, 'fmask', 1,npiglo,npjglo) ; !lolo
+   tmask =  getvar(cf_mm, 'tmask', 1,npiglo,npjglo) ; !lolo
+
+
+   tim=getvar1d(cfilu,trim(ctim),nt)
+   ierr=putvar1d(ncout,tim,nt,'T')
+
+   DO jt=1,nt
+
+      PRINT *, ' * [cdfcurl] jt = ', jt
+
+      ! if files are forcing fields
+      jk = ilev
+      zun(:,:) =  getvar(cfilu, cvaru, jk ,npiglo,npjglo, ktime=jt)
+      zvn(:,:) =  getvar(cfilv, cvarv, jk ,npiglo,npjglo, ktime=jt)
+
+      !! VU and VV on T-point:
+      un_t = 0.
+      DO ji=2, npiglo
+         un_t(ji,:) = 0.5*(zun(ji-1,:) + zun(ji,:))*tmask(ji,:)
+      END DO
+      vn_t = 0.
+      DO jj=2, npjglo
+         vn_t(:,jj) = 0.5*(zvn(:,jj-1) + zvn(:,jj))*tmask(:,jj)
+      END DO
+      
+      rotn(:,:) = 0.
+      DO jj = 1, npjglo -1
+         DO ji = 1, npiglo -1   ! vector opt.
+            rotn(ji,jj) = 1.E6 * (  e2v(ji+1,jj  ) * zvn(ji+1,jj  ) - e2v(ji,jj) * zvn(ji,jj)    &
+               &                   - e1u(ji  ,jj+1) * zun(ji  ,jj+1) + e1u(ji,jj) * zun(ji,jj)  ) &
+               &           * fmask(ji,jj) / ( e1f(ji,jj) * e2f(ji,jj) )
+         END DO
+      END DO
+      !
+      rotn(npiglo,:) = rotn(2,:) ; ! periodicity lolo
+      WHERE ( fmask == 0. ) rotn = -9999.
+
+      ! write rotn on file at level k and at time jt
+      ierr = putvar(ncout, id_varout(1), rotn, 1 ,npiglo, npjglo, jt)
+      
+      !! Wind stress module at T-point
+      taum(:,:) = 0.
+      taum(:,:) = SQRT( un_t(:,:)*un_t(:,:) + vn_t(:,:)*vn_t(:,:) )
+      taum(1,:) = taum(npiglo-1,:) ; ! periodicity lolo
+      WHERE ( tmask == 0. ) taum = -9999.
+      ierr = putvar(ncout, id_varout(2), taum, 1 ,npiglo, npjglo, jt)
+
+   END DO
+   ierr = closeout(ncout)
+   
+END PROGRAM cdfcurl
+

+ 238 - 0
cdftools_light/src/cdfhflx.f90

@@ -0,0 +1,238 @@
+PROGRAM cdfhflx
+  !!-------------------------------------------------------------------
+  !!               ***  PROGRAM cdfhflx  ***
+  !!
+  !!  **  Purpose  :  Compute the Meridional Heat Transport from the forcing fluxes
+  !!                  PARTIAL STEPS
+  !!  
+  !!  **  Method   :   Compute the zonaly integrated heat flux.
+  !!                  The program looks for the file "new_maskglo.nc". If it does not exist, 
+  !!                  only the calculation over all the domain is performed (this is adequate 
+  !!                  for a basin configuration like NATL4).
+  !!                  In new_maskglo.nc the masking corresponds to the global
+  !!                  configuration. (Global, Atlantic, Indo-Pacific, Indian,Pacific ocean)
+  !!
+  !!
+  !! history ;
+  !!  Original :  J.M. Molines (jul. 2005) 
+  !!              A.M. Treguier (april 2006) adaptation to NATL4 case 
+  !!              R. Dussin (Jul. 2009) : Add netcdf output
+  !!-------------------------------------------------------------------
+  !!  $Rev: 319 $
+  !!  $Date: 2010-05-19 12:19:07 +0200 (Wed, 19 May 2010) $
+  !!  $Id: cdfhflx.f90 319 2010-05-19 10:19:07Z dussin $
+  !!--------------------------------------------------------------
+  !! * Modules used
+  USE cdfio
+
+  !! * Local variables
+  IMPLICIT NONE
+  INTEGER   :: jpbasins
+  INTEGER   :: jbasin, jj, jk ,ji                  !: dummy loop index
+  INTEGER   :: ierr                                !: working integer
+  INTEGER   :: narg, iargc                         !: command line 
+  INTEGER   :: npiglo,npjglo, npk                  !: size of the domain
+  INTEGER   :: ncout, np, imean
+  INTEGER   :: numout=10
+  INTEGER, DIMENSION(2)          ::  iloc
+  ! added to write in netcdf
+  INTEGER :: kx=1, ky=1                ! dims of netcdf output file
+  INTEGER :: nboutput                  ! number of values to write in cdf output
+  INTEGER, DIMENSION(:), ALLOCATABLE ::  ipk, id_varout
+
+  REAL(KIND=4), DIMENSION (:,:),     ALLOCATABLE ::  e1t, e2t, gphit, zflx !:  metrics, velocity
+  REAL(KIND=4), DIMENSION (:,:,:),   ALLOCATABLE ::  zmask             !:  jpbasins x npiglo x npjglo
+  REAL(KIND=4), DIMENSION (:,:),     ALLOCATABLE ::  dumlon              !: dummy longitude = 0.
+  REAL(KIND=4), DIMENSION (:,:),     ALLOCATABLE ::  dumlat              !: latitude for i = north pole
+  REAL(KIND=4) ,DIMENSION(:,:) , ALLOCATABLE ::  gphimean,htrp    !: jpbasins x npjglo
+
+  REAL(KIND=8) ,DIMENSION(:,:) , ALLOCATABLE ::  zmht    !: jpbasins x npjglo 
+  ! added to write in netcdf
+  REAL(KIND=4) :: threedmeanout, pmissing_value
+  REAL(KIND=4), DIMENSION (1)               ::  tim ! time counter
+  REAL(KIND=4), DIMENSION(:), ALLOCATABLE :: meanout
+
+  TYPE(variable), DIMENSION(:), ALLOCATABLE :: typvar  ! structure of output
+
+  CHARACTER(LEN=256) :: cfilet , cfileout='hflx.out'
+  CHARACTER(LEN=256) :: coordhgr='mesh_hgr.nc',cbasinmask='new_maskglo.nc'
+  ! added to write in netcdf
+  CHARACTER(LEN=256) :: cfileoutnc='cdfhflx.nc' 
+  CHARACTER(LEN=256) :: cdunits, cdlong_name, cdshort_name
+
+  LOGICAL    :: llglo = .FALSE.                          !: indicator for presence of new_maskglo.nc file 
+  ! added to write in netcdf
+  LOGICAL :: lwrtcdf=.TRUE.
+
+  INTEGER    :: istatus
+
+  !!  Read command line and output usage message if not compliant.
+  narg= iargc()
+  IF ( narg == 1 ) THEN
+     CALL getarg (1, cfilet)
+     npiglo= getdim (cfilet,'x')
+     npjglo= getdim (cfilet,'y')
+     npk   = getdim (cfilet,'depth')
+
+     PRINT *, 'npiglo=', npiglo
+     PRINT *, 'npjglo=', npjglo
+     PRINT *, 'npk   =', npk
+  ELSE
+     PRINT *,' Usage : cdfhflx  T-file '
+     PRINT *,' Computes the MHT from heat fluxes '
+     PRINT *,' Files mesh_hgr.nc, new_maskglo.nc must be in the current directory '
+     PRINT *,' Output on hflx.out (ascii file ) and hflx.nc '
+     STOP
+  ENDIF
+
+  !  Detects newmaskglo file 
+  INQUIRE( FILE='new_maskglo.nc', EXIST=llglo )
+  IF (llglo) THEN
+     jpbasins = 5
+  ELSE
+     jpbasins = 1
+  ENDIF
+
+  ! Allocate arrays
+  ALLOCATE ( zmask(jpbasins,npiglo,npjglo) )
+  ALLOCATE ( zflx(npiglo,npjglo) )
+  ALLOCATE ( e1t(npiglo,npjglo),e2t(npiglo,npjglo), gphit(npiglo,npjglo) )
+  ALLOCATE ( htrp (jpbasins,npjglo) )
+  ALLOCATE ( zmht(jpbasins, npjglo) )
+  ALLOCATE ( dumlon(1,npjglo) , dumlat(1,npjglo))
+
+  IF (lwrtcdf) THEN
+     nboutput=jpbasins 
+     ALLOCATE (typvar(nboutput), ipk(nboutput), id_varout(nboutput))
+
+     DO jj=1,jpbasins
+        ipk(jj)=1
+     ENDDO
+
+     ! define new variables for output 
+     typvar(1)%name='hflx_glo'
+     typvar%units=TRIM(cdunits)
+     typvar%missing_value=99999.
+     typvar%valid_min= -1000.
+     typvar%valid_max= 1000.
+     typvar%scale_factor= 1.
+     typvar%add_offset= 0.
+     typvar%savelog10= 0.
+     typvar%units='PW' 
+     typvar(1)%long_name='Heat_Fluxes_Global'
+     typvar(1)%short_name='hflx_glo'
+     typvar%online_operation='N/A'
+     typvar%axis='ZT'
+
+     IF (llglo) THEN
+
+        typvar(2)%name='hflx_atl'
+        typvar(2)%long_name='Heat_Fluxes_Atlantic'
+        typvar(2)%short_name='hflx_atl'
+
+        typvar(3)%name='hflx_indopacif'
+        typvar(3)%long_name='Heat_Fluxes_Indo-Pacific'
+        typvar(3)%short_name='hflx_indopacif'
+
+        typvar(4)%name='hflx_indian'
+        typvar(4)%long_name='Heat_Fluxes_Indian'
+        typvar(4)%short_name='hflx_indian'
+
+        typvar(5)%name='hflx_pacif'
+        typvar(5)%long_name='Heat_Fluxes_Pacific'
+        typvar(5)%short_name='hflx_pacif'
+
+     ENDIF
+  ENDIF
+
+  e1t(:,:) = getvar(coordhgr, 'e1t', 1,npiglo,npjglo) 
+  e2t(:,:) = getvar(coordhgr, 'e2t', 1,npiglo,npjglo) 
+  gphit(:,:) = getvar(coordhgr, 'gphit', 1,npiglo,npjglo)
+
+  iloc=MAXLOC(gphit)
+  dumlat(1,:) = gphit(iloc(1),:)
+  dumlon(:,:) = 0.   ! set the dummy longitude to 0
+
+  ! reading the masks
+  ! 1 : global ; 2 : Atlantic ; 3 : Indo-Pacif ; 4 : Indian ; 5 : Pacif
+  zmask(1,:,:)=getvar('mask.nc','vmask',1,npiglo,npjglo)
+
+  IF (llglo) THEN
+     zmask(2,:,:)=getvar(cbasinmask,'tmaskatl',1,npiglo,npjglo)
+     zmask(4,:,:)=getvar(cbasinmask,'tmaskind',1,npiglo,npjglo)
+     zmask(5,:,:)=getvar(cbasinmask,'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
+     !       change global mask for GLOBAL periodic condition
+     zmask(1,1,:) = 0.
+     zmask(1,npiglo,:) = 0.
+  ENDIF
+
+  ! initialize zmht
+  zmht(:,:) = 0.
+  htrp(:,:) = 0.
+
+
+  ! Get fluxes
+  zflx(:,:)= getvar(cfilet, 'sohefldo',  1 ,npiglo,npjglo)
+
+  ! integrates 'zonally' (along i-coordinate)
+  DO ji=1,npiglo
+     ! For all basins 
+     DO jbasin = 1, jpbasins
+        DO jj=1,npjglo
+           zmht(jbasin,jj)=zmht(jbasin,jj) + e1t(ji,jj)*e2t(ji,jj)* zmask(jbasin,ji,jj)*zflx(ji,jj)
+        ENDDO
+     END DO
+  END DO
+
+  ! cumulates transport from north to south
+  DO jj=npjglo-1,1,-1
+     DO jbasin=1, jpbasins
+        htrp(jbasin,jj) = htrp(jbasin,jj+1) - zmht(jbasin,jj)
+     END DO
+  END DO
+
+  OPEN(numout,FILE=cfileout,FORM='FORMATTED', RECL=256)  ! to avoid wrapped line with ifort
+  WRITE(numout,*)'! Zonal heat transport (integrated from surface fluxes) (in Pw)'
+  IF (llglo) THEN
+     WRITE(numout,*)'! J        Global          Atlantic         INDO-PACIF    INDIAN  PACIF '
+     DO jj=npjglo, 1, -1
+        WRITE(numout,9000) jj, &
+             dumlat(1,jj),  htrp(1,jj)/1e15 , &
+             htrp(2,jj)/1e15, &
+             htrp(3,jj)/1e15, &
+             htrp(4,jj)/1e15, &
+             htrp(5,jj)/1e15
+     ENDDO
+  ELSE
+     WRITE(numout,*)'! J        Global   '
+     DO jj=npjglo, 1, -1
+        WRITE(numout,9000) jj, &
+             dumlat(1,jj),  htrp(1,jj)/1e15  
+     ENDDO
+  ENDIF
+
+  CLOSE(numout)
+9000 FORMAT(I4,5(1x,f9.3,1x,f8.4))
+
+  IF (lwrtcdf) THEN
+
+     ! create output fileset
+     ncout =create(cfileoutnc,'none',kx,npjglo,npk)
+     ierr= createvar(ncout,typvar,nboutput,ipk,id_varout )
+     ierr= putheadervar(ncout, cfilet ,kx, npjglo,npk,pnavlon=dumlon,pnavlat=dumlat)
+     tim=getvar1d(cfilet,'time_counter',1)
+     ierr=putvar1d(ncout,tim,1,'T')
+
+     ! netcdf output 
+     DO jj=1, jpbasins
+        ierr = putvar(ncout, id_varout(jj), htrp(jj,:)/1e15, ipk(jj), kx, npjglo )
+     END DO
+
+     ierr = closeout(ncout)
+
+  ENDIF
+
+END PROGRAM cdfhflx

+ 260 - 0
cdftools_light/src/cdficediags.f90

@@ -0,0 +1,260 @@
+PROGRAM cdficediag
+  !!-------------------------------------------------------------------
+  !!               ***  PROGRAM cdficediag  ***
+  !!
+  !!  **  Purpose  :  Compute the Ice volume, area and extend for each hemisphere
+  !!
+  !!  **  Method   :   Read the ice output and integrates (2D)
+  !!                   determine the hemisphere by the sign of ff (coriolis)
+  !!
+  !! history ;
+  !!  Original :  J.M. Molines (Jan. 2006)
+  !!              R. Dussin (Jul. 2009) : Add netcdf output
+  !!-------------------------------------------------------------------
+  !!  $Rev: 319 $
+  !!  $Date: 2010-05-19 12:19:07 +0200 (Wed, 19 May 2010) $
+  !!  $Id: cdficediags.f90 319 2010-05-19 10:19:07Z dussin $
+  !!--------------------------------------------------------------
+  !! * Modules used
+  USE netcdf
+
+  USE cdfio
+
+  !! * Local variables
+  IMPLICIT NONE
+  INTEGER   :: jk, jj, jt !LB
+  INTEGER   :: ierr                                !: working integer
+  INTEGER   :: narg, iargc                         !: command line
+  INTEGER   :: npiglo,npjglo, nt !LB               !: size of the domain
+  INTEGER   :: nvpk                                !: vertical levels in working variable
+  INTEGER   :: nperio = 4                          !: boundary condition ( periodic, north fold)
+
+  REAL(KIND=4), DIMENSION (:,:),   ALLOCATABLE ::  e1, e2            !:  metrics
+  REAL(KIND=4), DIMENSION (:,:),   ALLOCATABLE ::  zmask ,ff         !:   npiglo x npjglo
+  REAL(KIND=4), DIMENSION (:,:),   ALLOCATABLE ::  ricethick, riceldfra !: thickness, leadfrac (concentration)
+
+  REAL(KIND=8)      :: zvols,  zareas, zextends,zextends2        !: volume, area extend South hemisphere
+  REAL(KIND=8)      :: zvoln,  zarean, zextendn,zextendn2        !: volume, area extend North hemisphere
+
+  REAL(KIND=8), DIMENSION (:), ALLOCATABLE  :: vvolu_n, varea_n, vvolu_s, varea_s
+
+
+
+  CHARACTER(LEN=3)   :: conly_c='000' !lolo
+  CHARACTER(LEN=256) :: cf_ice , cdum, ctim
+  CHARACTER(LEN=256) :: cf_mm='mesh_mask.nc'
+
+  INTEGER    :: istatus
+
+  !! LOLO:
+  LOGICAL :: lfncout = .FALSE., l_in_percent = .FALSE.
+  CHARACTER(LEN=256) :: cd_out = '.', cf_out
+  CHARACTER(LEN=64)  :: cv_u, cv_v, cv_ueiv, cv_veiv, cv_dum
+  REAL :: ryear
+  INTEGER :: jt_pos, idf_out, idd_t, idv_time
+  INTEGER :: id_volu_n, id_area_n, id_volu_s, id_area_s
+  !! LOLO.
+
+
+
+  ! constants
+
+  !!  Read command line and output usage message if not compliant.
+  narg= iargc()
+  IF ( narg >= 3) THEN
+     CALL getarg (1, cf_ice)
+     npiglo = getdim (cf_ice,'x')
+     npjglo = getdim (cf_ice,'y')
+     ctim = 'none'
+     nt    = getdim (cf_ice,'time',cdtrue=ctim,kstatus=istatus) !LB
+     CALL getarg (2, cdum)  ; READ(cdum,*) ryear
+     CALL getarg (3, cd_out)
+     IF ( narg == 4) CALL getarg (4, conly_c)
+  ELSE
+     PRINT *,' Usage : cdficediag.x <ice_file> <year> <DIROUT>'
+     PRINT *,' File mesh_mask.nc must be in the current directory'
+     STOP
+  ENDIF
+
+  ALLOCATE ( zmask(npiglo,npjglo) ,ff(npiglo,npjglo) )
+  ALLOCATE ( ricethick(npiglo,npjglo) )
+  ALLOCATE ( riceldfra(npiglo,npjglo) )
+  ALLOCATE ( e1(npiglo,npjglo),e2(npiglo,npjglo) )
+  !ALLOCATE ( tim(nt) ) !LB
+  !tim = getvar1d(cf_ice,trim(ctim),nt) !LB
+
+
+  e1(:,:) = getvar(cf_mm, 'e1t', 1,npiglo,npjglo)
+  e2(:,:) = getvar(cf_mm, 'e2t', 1,npiglo,npjglo)
+  ! only the sign of ff is important
+  ff(:,:) = getvar(cf_mm, 'gphit' , 1,npiglo,npjglo)
+
+
+  ! 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 ...
+
+  zmask(:,:)=getvar(cf_mm,'tmask',1,npiglo,npjglo)
+  SELECT CASE (nperio)
+  CASE (0) ! closed boundaries
+     ! nothing to do
+  CASE (4) ! ORCA025 type boundary
+     zmask(1:2,:)=0.
+     zmask(:,npjglo)=0.
+     zmask(npiglo/2+1:npiglo,npjglo-1)= 0.
+  CASE (6)
+     zmask(1:2,:)=0.
+     zmask(:,npjglo)=0.
+  CASE DEFAULT
+     PRINT *,' Nperio=', nperio,' not yet coded'
+     STOP
+  END SELECT
+
+
+
+
+  ALLOCATE ( vvolu_n(nt), varea_n(nt), vvolu_s(nt), varea_s(nt) )
+
+  DO jt = 1, nt
+
+     PRINT *, ' * [cdficediags] jt = ', jt
+     
+     IF ( conly_c == '000' ) THEN
+        ricethick(:,:)= getvar(cf_ice, 'ice_thic',  1 ,npiglo,npjglo, ktime=jt)
+     END IF
+     riceldfra(:,:)= getvar(cf_ice, 'ice_frac',  1 ,npiglo,npjglo, ktime=jt)
+     
+     IF ( jt == 1 ) THEN
+        ! Is fraction in percent rather than fraction ?
+        IF ( MAXVAL( zmask*riceldfra ) > 30. ) l_in_percent = .TRUE.
+     END IF
+     IF ( l_in_percent ) riceldfra = 0.01 * riceldfra
+     
+     WHERE ( zmask == 0. )
+        ricethick = 0.
+        riceldfra = 0.
+     END WHERE
+
+     ! North : ff > 0
+     zvoln=SUM( ricethick (:,:)* e1(:,:) * e2(:,:) * riceldfra (:,:) * zmask (:,:) , (ff > 0 ) )
+
+     zarean=SUM( e1(:,:) * e2(:,:) * riceldfra (:,:) * zmask (:,:) ,( ff > 0 ) )
+     zextendn=SUM( e1(:,:) * e2(:,:) * riceldfra (:,:) * zmask (:,:), (riceldfra > 0.15 .AND. ff > 0 ) )
+     ! JMM added 22/01/2007 : to compute same extent than the NSIDC
+     zextendn2=SUM( e1(:,:) * e2(:,:) * zmask (:,:), (riceldfra > 0.15 .AND. ff > 0 ) )
+
+     ! South : ff < 0
+     zvols=SUM( ricethick (:,:)* e1(:,:) * e2(:,:) * riceldfra (:,:) * zmask (:,:) ,(ff < 0 ) )
+
+     zareas=SUM( e1(:,:) * e2(:,:) * riceldfra (:,:) * zmask (:,:), ( ff < 0 ) )
+     zextends=SUM( e1(:,:) * e2(:,:) * riceldfra (:,:) * zmask (:,:), (riceldfra > 0.15 .AND. ff < 0  ) )
+     zextends2=SUM( e1(:,:) * e2(:,:)* zmask (:,:), (riceldfra > 0.15 .AND. ff < 0  ) )
+
+     vvolu_n(jt) =  zvoln/1.d12
+     varea_n(jt) =  zarean/1.d12
+     vvolu_s(jt) =  zvols/1.d12
+     varea_s(jt) =  zareas/1.d12
+
+
+     !LB:
+     !IF ( jt == 1 ) THEN
+     !   OPEN(UNIT=12, FILE='ice.dat', FORM='FORMATTED', RECL=256, STATUS='unknown')
+     !   WRITE(12,*) ' #    month  N.Volume (10^3km^3)      N.Area (10^6km^2)     S.Volume (10^3km^3)    S.Area (10^6km^2)'
+     !END IF
+     !
+     !WRITE(12,*) jt, zvoln /1.d12, zarean /1.d12, zvols /1.d12, zareas /1.d12
+
+
+     !PRINT *,' Northern Hemisphere '
+     !PRINT *,'          NVolume (10^9 m3)  ', zvoln /1.d9
+     !PRINT *,'          NArea (10^9 m2)    ', zarean /1.d9
+     !PRINT *,'          NExtend (10^9 m2)  ', zextendn /1.d9
+     !PRINT *,'          NExnsidc (10^9 m2)  ', zextendn2 /1.d9
+     !PRINT *
+     !PRINT *,' Southern Hemisphere '
+     !PRINT *,'          SVolume (10^9 m3)  ', zvols /1.d9
+     !PRINT *,'          SArea (10^9 m2)    ', zareas /1.d9
+     !PRINT *,'          SExtend (10^9 m2)  ', zextends /1.d9
+     !PRINT *,'          SExnsidc (10^9 m2)  ', zextends2 /1.d9
+
+
+  END DO ! DO jt = 1, nt
+
+
+
+
+  !! Time to create or append X_trsp into the netcdf file for current section
+  !! -----------------------------------------------------
+
+  WRITE(cf_out, '(a,"/seaice_diags.nc")') trim(cd_out)
+
+  id_volu_n = 0 ; id_area_n = 0 ; id_volu_s = 0
+  
+  !! LOLO netcdf
+  INQUIRE( FILE=cf_out, EXIST=lfncout )
+  
+  IF ( .NOT. lfncout ) THEN
+     
+     !! Creating file
+     PRINT *, ' Creating file '//trim(cf_out)//' !!!'
+     ierr = NF90_CREATE(cf_out, NF90_CLOBBER, idf_out)
+     ierr = NF90_DEF_DIM(idf_out, 'time', NF90_UNLIMITED, idd_t)
+     ierr = NF90_DEF_VAR(idf_out, 'time', NF90_DOUBLE,    idd_t, idv_time)
+     
+     ierr = NF90_DEF_VAR(idf_out, 'volu_ne', NF90_FLOAT, (/idd_t/), id_volu_n)
+     ierr = NF90_DEF_VAR(idf_out, 'area_ne', NF90_FLOAT, (/idd_t/), id_area_n)
+     ierr = NF90_DEF_VAR(idf_out, 'volu_se', NF90_FLOAT, (/idd_t/), id_volu_s)
+     ierr = NF90_DEF_VAR(idf_out, 'area_se', NF90_FLOAT, (/idd_t/), id_area_s)
+     
+     ierr = NF90_PUT_ATT(idf_out, id_volu_n, 'long_name', 'Total volume of sea-ice in Northern Hemisphere')
+     ierr = NF90_PUT_ATT(idf_out, id_area_n, 'long_name', 'Total area of sea-ice in Northern Hemisphere')
+     ierr = NF90_PUT_ATT(idf_out, id_volu_s, 'long_name', 'Total volume of sea-ice in Southern Hemisphere')
+     ierr = NF90_PUT_ATT(idf_out, id_area_s, 'long_name', 'Total area of sea-ice in Southern Hemisphere')
+     
+     ierr = NF90_PUT_ATT(idf_out, id_volu_n, 'units', '10^3km^3')
+     ierr = NF90_PUT_ATT(idf_out, id_area_n, 'units', '10^6km^2')
+     ierr = NF90_PUT_ATT(idf_out, id_volu_s, 'units', '10^3km^3')
+     ierr = NF90_PUT_ATT(idf_out, id_area_s, 'units', '10^6km^2')
+     
+     !ierr = NF90_PUT_ATT(idf_out, NF90_GLOBAL, 'Info', 'Reference temperature for heat transport is '//trim(crt)//' deg.C')
+     ierr = NF90_PUT_ATT(idf_out, NF90_GLOBAL, 'About', &
+        &   'Created by BaraKuda (cdficediags.f90) => https://github.com/brodeau/barakuda')
+     
+     ierr = NF90_ENDDEF(idf_out)
+     jt_pos = 0
+     
+  ELSE
+     
+     !! Opening already existing file
+     ierr = NF90_OPEN  (cf_out, NF90_WRITE,   idf_out)
+
+     !! Need IDs of variables to append... NF90_INQ_VARID
+     ierr = NF90_INQ_VARID(idf_out, 'volu_ne', id_volu_n)
+     ierr = NF90_INQ_VARID(idf_out, 'area_ne', id_area_n)
+     ierr = NF90_INQ_VARID(idf_out, 'volu_se', id_volu_s)
+     ierr = NF90_INQ_VARID(idf_out, 'area_se', id_area_s)
+     
+     ! Get ID of unlimited dimension
+     ierr = NF90_INQUIRE(idf_out, unlimitedDimId = idv_time)
+     
+     ! Need to know jt_pos, record number of the last time record writen in the file
+     ierr = NF90_INQUIRE_DIMENSION(idf_out, idv_time, name=cv_dum, len=jt_pos)
+     
+  END IF
+  
+  WRITE(*,'("Going to write record ",i4.4," to ",i4.4," into ",a)') jt_pos+1, jt_pos+1+nt, trim(cf_out)
+
+  DO jt = 1, nt
+
+     ! Writing record jt for time vector and 1d fields:
+     ierr = NF90_PUT_VAR( idf_out, idv_time, (/ryear+1./12.*(REAL(jt)-1.+0.5)/), start=(/jt_pos+jt/), count=(/1/) )
+     
+     ierr = NF90_PUT_VAR(idf_out, id_volu_n, (/ vvolu_n(jt) /), start=(/jt_pos+jt/), count=(/1/))
+     ierr = NF90_PUT_VAR(idf_out, id_area_n, (/ varea_n(jt) /), start=(/jt_pos+jt/), count=(/1/))
+     ierr = NF90_PUT_VAR(idf_out, id_volu_s, (/ vvolu_s(jt) /), start=(/jt_pos+jt/), count=(/1/))
+     ierr = NF90_PUT_VAR(idf_out, id_area_s, (/ varea_s(jt) /), start=(/jt_pos+jt/), count=(/1/))
+     
+  END DO
+  
+  ierr = NF90_CLOSE(idf_out)
+  
+END PROGRAM cdficediag

+ 659 - 0
cdftools_light/src/cdficeflux.f90

@@ -0,0 +1,659 @@
+PROGRAM cdficeflux
+
+   !!---------------------------------------------------------------------
+   !!               ***  PROGRAM cdficeflux  ***
+   !!
+   !!  ** 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 :
+   !!               -time   : specify the time frame to be used
+   !!            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 netcdf
+
+   USE cdfio
+
+   IMPLICIT NONE
+
+   REAL(8) :: &
+      &        ref_sali0 = 34.8 ! reference salinity (in PSU)
+   CHARACTER(len=128) :: cref2='34.8'
+
+   CHARACTER(len=256) :: cf_sections
+
+   INTEGER(KIND=4)                             :: jseg   ! dummy loop index
+   INTEGER(KIND=4)                             :: ji, jj, jk     ! dummy loop index
+   INTEGER(KIND=4), DIMENSION(:),  ALLOCATABLE :: ipk, id_varout ! Netcdf output
+   INTEGER(KIND=4)                             :: ipos           ! working integer (position of ' ' in strings)
+   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)                             :: 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)                             :: 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)                             :: numin   = 10   ! logical unit for input section file (overall) !LB
+   INTEGER(KIND=4)                             :: numout  = 11   ! logical unit for output file (overall)
+   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, jt    ! 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 :: e1t, e2t       ! horizontal metric
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: glamf          ! longitudes of F points
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: gphif          ! latitudes of F points
+   !LB:
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: zu_i, zv_i, zc_i, zh_i ! velocities, concentration and thickness of sea-ice
+   !LB.
+   REAL(KIND=4), DIMENSION(:,:),   ALLOCATABLE :: rdum           ! dummy (1x1) array for ncdf output
+   REAL(KIND=4), DIMENSION(:),     ALLOCATABLE :: tim            ! time counter
+   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)                                :: dvoltrpsum, ryear     ! LB
+   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
+
+   ! at every model point
+   REAL(KIND=8), DIMENSION(:,:),   ALLOCATABLE :: dwku, dwkv, xtmp  ! volume transport at each cell boundary
+
+   ! for a given section
+
+   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)                                :: 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) , PARAMETER              :: cn_fmm = 'mesh_mask.nc'
+
+   CHARACTER(LEN=256)                          :: cf_icefil, cdum      ! seaice file   (in) !LB
+   CHARACTER(LEN=4)                            :: cyear
+   CHARACTER(LEN=256)                          :: cv_iceF, cv_iceU, cv_iceV, cv_iceH
+   CHARACTER(LEN=256)                          :: cf_out         ! output file name (ASCII)
+   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
+
+   CHARACTER(LEN=20) :: ce1, ce2, cvmask
+
+
+   LOGICAL                 :: ltest    = .FALSE.   ! flag for test case
+   LOGICAL                 :: lchk     = .FALSE.   ! flag for missing files
+   LOGICAL                 :: lconc_pc = .FALSE.  ! ice concentration is in percent!
+
+   CHARACTER(LEN=64)  :: cv_dum
+   CHARACTER(LEN=512) :: cd_out
+   LOGICAL                 :: lfncout = .FALSE.
+   INTEGER :: ierr, jt_pos, idf_out, idd_t, idv_time, id_frwt
+
+   REAL(4), DIMENSION(:), ALLOCATABLE :: X_trsp   ! lolo
+
+   !!----------------------------------------------------------------------
+   !CALL ReadCdfNames()
+
+   narg= iargc()
+   ! Print usage if no argument
+   IF ( narg < 8 ) THEN
+      PRINT *,' usage : cdficeflux <file_section_ASCII> <ICEMOD-file> <ice_conc> \\'
+      PRINT *, '                   <ice_veloc_u> <ice_veloc_v> <ice_volume> <year> <DIROUT>'
+      PRINT *,'      '
+      PRINT *,'    PURPOSE :'
+      PRINT *,'      Compute the transports of solid freshwater 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 *,'      '
+      PRINT *,'     ARGUMENTS :'
+      PRINT *,'      [ICEMOD-file] : netcdf file with the zonal velocity component.'
+      PRINT *,'      [ice_conc]    : name of ice concentration (0<= ... <=1)'
+      PRINT *,'      [ice_veloc_u] : name of ice velocity along i (m/s)'
+      PRINT *,'      [ice_veloc_v] : name of ice velocity along j (m/s)'
+      PRINT *,'      [ice_volume]  : name of ice volume/thickness (m) '
+      PRINT *,'      [year]        : Year'
+      PRINT *,'      [DIROUT]      : directory where to write netcdf file'
+      PRINT *,'      '
+      PRINT *,'      '
+      PRINT *,'     REQUIRED FILES :'
+      PRINT *,'      File ',TRIM(cn_fmm),' must be in the current directory.'
+      PRINT *,'      '
+      PRINT *,'     OUTPUT : '
+      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
+
+   jt  = 1
+   ijarg  = 1
+
+   CALL getarg (1, cf_sections)
+   CALL getarg (2, cf_icefil)
+   CALL getarg (3, cv_iceF)
+   CALL getarg (4, cv_iceU)
+   CALL getarg (5, cv_iceV)
+   CALL getarg (6, cv_iceH)
+   CALL getarg (7, cyear)    ; READ(cyear,*) ryear
+   CALL getarg (8, cd_out)
+
+   PRINT *, '   *** Ice concentration => ', TRIM(cv_iceF)
+   PRINT *, '   *** Ice U-velocity    => ', TRIM(cv_iceU)
+   PRINT *, '   *** Ice V-velocity    => ', TRIM(cv_iceV)
+   PRINT *, '   *** Ice thickness     => ', TRIM(cv_iceH)
+   PRINT *, ''
+
+   ce1='e1t'
+   ce2='e2t'
+   cvmask='tmask'
+
+
+   ! adjust the number of output variables according to options
+   nvarout = 1
+
+
+   npiglo = getdim (cf_icefil,'x')
+   npjglo = getdim (cf_icefil,'y')
+   npt    = getdim (cf_icefil,'time')
+
+   PRINT *, 'npiglo =', npiglo
+   PRINT *, 'npjglo =', npjglo
+   PRINT *, 'npt    =', npt
+
+   ! define new variables for output
+   ALLOCATE ( stypvar(nvarout), ipk(nvarout), id_varout(nvarout) )
+   ALLOCATE ( rdum(1,1) )
+
+   rdum(:,:)=0.e0
+
+   ! Allocate arrays
+   ALLOCATE ( zu_i(npiglo,npjglo),  zv_i(npiglo,npjglo), zc_i(npiglo,npjglo),  zh_i(npiglo,npjglo) )
+   ALLOCATE ( dwku(npiglo,npjglo), dwkv(npiglo,npjglo), xtmp(npiglo,npjglo) )
+
+
+   ALLOCATE ( e1t(npiglo,npjglo) )
+   ALLOCATE ( e2t(npiglo,npjglo) )
+   !
+   ALLOCATE ( gphif(npiglo,npjglo) )
+   ALLOCATE ( glamf(npiglo,npjglo) )
+   ALLOCATE ( tim(npt)                       )
+   !
+   ALLOCATE( X_trsp(npt) )
+
+
+   ! read metrics and grid position
+   e1t(:,:)   = getvar(cn_fmm, ce1, 1, npiglo, npjglo)
+   e2t(:,:)   = getvar(cn_fmm, ce2, 1, npiglo, npjglo)
+
+   glamf(:,:) = getvar(cn_fmm, 'glamf', 1,npiglo, npjglo)
+   gphif(:,:) = getvar(cn_fmm, 'gphif', 1,npiglo, npjglo)
+
+
+   DO WHILE ( 1 == 1 )
+      OPEN(numin, FILE=TRIM(cf_sections), status='old')
+      READ(numin,'(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
+         !PRINT *, 'LB! exiting'
+         CLOSE(numin)
+         GOTO 1111 ; ! LB
+         !EXIT  ! infinite DO loop
+      ENDIF
+      PRINT *, ''
+      PRINT *, '   cdficeflux: doing section '//trim(csection)
+
+
+      DO jt = 1, npt   !LB
+
+         PRINT *, ' * [cdficeflux] jt = ', jt
+
+         ! compute the transports at each grid cell
+
+         ! Get velocities, concentration and thickness for sea-ice:
+         IF ( ltest ) THEN
+            zu_i (:,:) = udum ; zv_i (:,:) = vdum
+         ELSE
+            zu_i (:,:) = getvar(cf_icefil, cv_iceU, 1, npiglo, npjglo, ktime=jt) ; ! LB
+            zv_i (:,:) = getvar(cf_icefil, cv_iceV, 1, npiglo, npjglo, ktime=jt) ; ! LB
+         ENDIF
+         zc_i (:,:) = getvar(cf_icefil, cv_iceH, 1, npiglo, npjglo, ktime=jt) ; ! LB
+         zh_i (:,:) = getvar(cf_icefil, cv_iceF, 1, npiglo, npjglo, ktime=jt) ; ! LB
+         !LB2JM: add all the ice variables into modcdfnames?
+
+         !LB: testing if concentration is a fraction or a percentage:
+         IF ( (jt==1).AND.(MAXVAL(zc_i (npiglo/2,:)) > 2.) ) lconc_pc = .TRUE.
+         IF (lconc_pc) zc_i(:,:) = 0.01*zc_i(:,:)
+         
+         !LB:
+         !! Volume of ice transport at each grid point:
+         !!  => concentration * thickness * u * dy
+         !!  => concentration * thickness * v * dx
+         xtmp(:,:) = zh_i(:,:)*zc_i(:,:)
+         dwku(:,:) = xtmp(:,:)*zu_i(:,:)*e2t(:,:)*1.d0
+         dwkv(:,:) = xtmp(:,:)*zv_i(:,:)*e1t(:,:)*1.d0
+
+
+         IF ( jt == 1 ) THEN   !LB
+
+            READ(numin,*) 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
+            
+            !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=(e2t*idiry,-e1t*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
+
+         END IF ! jt == 1
+
+
+         ! Now really calculate the flux for time jt!
+
+         dvoltrpsum   = 0.d0
+
+         ! 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) = dwku(ii0,ij0+ijst)*norm_u
+
+            ELSE IF ( ryy(jseg) == ryy(jseg+1) ) THEN ! zonal segment, use V velocity
+               dvoltrp(jseg) = dwkv(ii0+iist,ij0)*norm_v
+
+            ELSE
+               PRINT *,' ERROR :',  rxx(jseg),ryy(jseg),rxx(jseg+1),ryy(jseg+1) ! likely to never happen !
+            END IF
+
+            dvoltrpsum = dvoltrpsum + dvoltrp(jseg)
+
+         END DO   ! next segment
+
+
+         !! Correcting value, due to expension of ice and salinity of ice:
+         dvoltrpsum = 0.92*dvoltrpsum   ; ! 1m^3 of ice makes 0.92 m^3 of water
+
+         dvoltrpsum = dvoltrpsum * ( ref_sali0 - 4. )/ref_sali0  ; ! salinity of sea-ice taken as 4 PSU
+         !!                                              ! referencesalinity for Arctic: 34.8 PSU
+
+         X_trsp(jt) = dvoltrpsum/1.e6  ! (Sv)
+
+
+      END DO ! loop on time steps ( jt = 1 => npt
+
+
+      PRINT *, ''
+
+      !! Time to create or append X_trsp into the netcdf file for current section
+      !! -----------------------------------------------------
+
+      id_frwt = 0
+
+      WRITE(cf_out, '(a,"/transport_ice_sect_",a,".nc")') trim(cd_out), trim(csection)
+
+      INQUIRE( FILE=cf_out, EXIST=lfncout )
+
+      IF ( .NOT. lfncout ) THEN
+
+         !! Creating file
+         PRINT *, ' Creating file '//TRIM(cf_out)//' !!!'
+         ierr = NF90_CREATE(cf_out, NF90_CLOBBER, idf_out)
+         ierr = NF90_DEF_DIM(idf_out, 'time', NF90_UNLIMITED, idd_t)
+         ierr = NF90_DEF_VAR(idf_out, 'time', NF90_DOUBLE,    idd_t, idv_time)
+
+
+         ierr = NF90_DEF_VAR(idf_out, 'trsp_frwt', NF90_FLOAT, (/idd_t/), id_frwt)
+         ierr = NF90_PUT_ATT(idf_out, id_frwt, 'long_name', 'Transport of (solid) freshwater due to sea-ice drift')
+         ierr = NF90_PUT_ATT(idf_out, id_frwt, 'units', 'Sv')
+         ierr = NF90_PUT_ATT(idf_out, id_frwt, 'Sref', cref2)
+         ierr = NF90_PUT_ATT(idf_out, NF90_GLOBAL, 'About', &
+            &   'Created by BaraKuda (cdficeflux.x) => https://github.com/brodeau/barakuda')
+
+         ierr = NF90_ENDDEF(idf_out)
+         jt_pos = 0
+
+
+      ELSE
+
+         !! Opening already existing file
+         ierr = NF90_OPEN  (cf_out, NF90_WRITE,   idf_out)
+
+         !! Need IDs of variables to append... NF90_INQ_VARID
+         ierr = NF90_INQ_VARID(idf_out, 'trsp_frwt', id_frwt)
+
+         ! Get ID of unlimited dimension
+         ierr = NF90_INQUIRE(idf_out, unlimitedDimId = idv_time)
+
+         ! Need to know jt_pos, record number of the last time record writen in the file
+         ierr = NF90_INQUIRE_DIMENSION(idf_out, idv_time, name=cv_dum, len=jt_pos)
+
+      END IF
+
+      WRITE(*,'("Going to write record ",i4.4," to ",i4.4," into ",a)') jt_pos+1, jt_pos+npt, trim(cf_out)
+
+      DO jt = 1, npt
+
+         ! Writing record jt for time vector and 1d fields:
+         ierr = NF90_PUT_VAR( idf_out, idv_time, (/ryear+1./12.*(REAL(jt)-1.+0.5)/), start=(/jt_pos+jt/), count=(/1/) )
+
+         !! Default variable is the only one present (index = 1) :
+         ierr = NF90_PUT_VAR(idf_out, id_frwt, (/ X_trsp(jt) /), start=(/jt_pos+jt/), count=(/1/))
+
+      END DO
+
+      ierr = NF90_CLOSE(idf_out)
+
+
+
+   END DO ! infinite loop : gets out when input is EOF
+
+
+
+
+1111 CONTINUE
+
+
+
+
+
+
+
+
+CONTAINS
+
+
+
+   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 cdficeflux

+ 1961 - 0
cdftools_light/src/cdfio.f90

@@ -0,0 +1,1961 @@
+ MODULE cdfio
+  !!---------------------------------------------------------------------------------------------------
+  !!                     ***  MODULE  cdfio  ***
+  !!
+  !!    ** Purpose : this module manage all the IO with Netcdf Library
+  !!
+  !!    ** Method : provide functions that are used in the different
+  !!                 subprograms for performing dedicated tasks
+  !!  
+  !!   history:
+  !!         Original : J.M. Molines (2005 )
+  !!                    R. Dussin (2009) add putvar_0d function
+  !!------------------------------------------------------------------------------------------------------
+  !!  $Rev: 317 $
+  !!  $Date: 2010-05-17 14:47:12 +0200 (Mon, 17 May 2010) $
+  !!  $Id: cdfio.f90 317 2010-05-17 12:47:12Z molines $
+  !!--------------------------------------------------------------
+  USE netcdf 
+
+  IMPLICIT NONE
+  INTEGER :: id_x, id_y, id_z, id_t, id_lat, id_lon, id_dep, id_tim
+  LOGICAL :: l_mbathy=.false.
+  INTEGER,    DIMENSION(:,:), ALLOCATABLE :: mbathy            !: for reading e3._ps in nemo3.x
+  REAL(kind=4),  DIMENSION(:,:), ALLOCATABLE :: e3t_ps, e3w_ps !: for reading e3._ps in nemo3.x
+! REAL(kind=4),  DIMENSION(:,:), ALLOCATABLE :: e3u_ps, e3v_ps !: for reading e3._ps in nemo3.x
+  REAL(kind=4),  DIMENSION(:), ALLOCATABLE :: e3t_0, e3w_0 !: for readinf e3._ps in nemo3.x
+
+  TYPE, PUBLIC ::   variable 
+     CHARACTER(LEN=256)::  name
+     CHARACTER(LEN=256):: units
+     REAL(kind=4)    :: missing_value
+     REAL(kind=4)    :: valid_min
+     REAL(kind=4)    :: valid_max
+     REAL(kind=4)    :: scale_factor=1.
+     REAL(kind=4)    :: add_offset=0.
+     REAL(kind=4)    :: savelog10=0.
+     INTEGER         :: iwght=1
+     CHARACTER(LEN=256):: long_name
+     CHARACTER(LEN=256):: short_name
+     CHARACTER(LEN=256):: online_operation
+     CHARACTER(LEN=256):: axis
+     CHARACTER(LEN=256):: PRECISION='r4'  ! possible values are i2, r4, r8
+  END TYPE variable
+
+  INTERFACE putvar
+     MODULE PROCEDURE putvarr8, putvarr4, putvari2, putvarzo, reputvarr4
+  END INTERFACE
+
+
+  PRIVATE 
+  PUBLIC  copyatt, create, createvar, getvaratt,cvaratt
+  PUBLIC  putatt, putheadervar, putvar, putvar1d, putvar0d
+  PUBLIC  getatt, getdim, getvdim, getipk, getnvar, getvarname, getvarid, getspval
+  PUBLIC  getvar, getvarxz, getvaryz, getvar1d, getvare3
+  PUBLIC gettimeseries
+  PUBLIC closeout, ncopen
+  PUBLIC ERR_HDL
+
+
+CONTAINS
+  FUNCTION copyatt(cdvar,kidvar,kcin,kcout)
+    !! ----------------------------------------------------------------------------------------------------
+    !!  *** Copy attributes for variable cdvar, which have id kidvar in kcout, from file id kcin
+    !!
+    !! ----------------------------------------------------------------------------------------------------
+    ! * Arguments
+    INTEGER, INTENT(in) :: kidvar, kcout
+    INTEGER,  INTENT(in) :: kcin
+    CHARACTER(LEN=*), INTENT(in) :: cdvar
+    INTEGER :: copyatt
+
+    ! * Local variable
+    INTEGER :: istatus, idvar, iatt, ja
+    CHARACTER(LEN=256) :: clatt
+
+    IF ( kcin /= -9999) THEN
+       istatus = NF90_INQ_VARID(kcin,cdvar,idvar)
+       istatus = NF90_INQUIRE_VARIABLE(kcin,idvar,natts=iatt)
+       DO ja = 1, iatt
+          istatus = NF90_INQ_ATTNAME(kcin,idvar,ja,clatt)
+          istatus = NF90_COPY_ATT(kcin,idvar,clatt,kcout,kidvar)
+       END DO
+    ELSE
+       SELECT CASE (cdvar )
+       CASE ('nav_lon' )
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'units', 'degrees_east')
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'valid_min', -180.)
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'valid_max', 180.)
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'long_name', 'Longitude')
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'nav_model', 'Default grid')
+       CASE ('nav_lat' )
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'units', 'degrees_north')
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'valid_min', -90.)
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'valid_max', 90.)
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'long_name', 'Latitude')
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'nav_model', 'Default grid')
+       CASE ('time_counter' )
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'calendar', 'gregorian')
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'units', 'seconds since 0006-01-01 00:00:00')
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'time_origin', '0001-JAN-01 00:00:00')
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'title', 'Time')
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'long_name', 'Time axis')
+       CASE ('deptht', 'depthu' ,'depthv' , 'depthw', 'dep')
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'units', 'm')
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'positive', 'unknown')
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'valid_min', 0.)
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'valid_max', 5875.)
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'title', TRIM(cdvar))
+          istatus=NF90_PUT_ATT(kcout, kidvar, 'long_name', 'Vertical Levels')
+       END SELECT
+    ENDIF
+
+    copyatt = istatus
+  END FUNCTION copyatt
+
+
+  FUNCTION create( cdfile, cdfilref ,kx,ky,kz ,cdep, cdepvar)
+    !! ------------------------------------------------------------------------------------------
+    !! ***  Create the file, and creates dimensions, and copy attributes from a cdilref
+    !!      reference file ( for the nav_lon, nav_lat etc ...)
+    !!      If optional cdep given : take as depth variable name instead of cdfilref
+    !!      Return the nc id of the created file, and leave it open
+    !!
+    !! ------------------------------------------------------------------------------------------
+    ! * Arguments
+    CHARACTER(LEN=*), INTENT(in) :: cdfile,cdfilref
+    INTEGER, INTENT(in) :: kx,ky,kz
+    CHARACTER(LEN=*), OPTIONAL, INTENT(in) :: cdep    !: name of vertical dim name if not standard
+    CHARACTER(LEN=*), OPTIONAL, INTENT(in) :: cdepvar !: name of vertical var name if it differs
+                                                      !:  from vertical dimension name
+    INTEGER :: create
+
+    ! * Local Variable
+    INTEGER   :: istatus, icout,ncid, idum
+    INTEGER ,DIMENSION(4) :: nvdim
+    CHARACTER(LEN=256) :: cldep, cldepref, cldepvar
+
+    istatus = NF90_CREATE(cdfile,NF90_CLOBBER, icout)
+    istatus = NF90_DEF_DIM(icout,'x',kx, id_x)
+    istatus = NF90_DEF_DIM(icout,'y',ky, id_y)
+
+    IF ( kz /= 0 ) THEN
+       ! try to find out the name I will use for depth dimension in the new file ...
+       IF (PRESENT (cdep) ) THEN
+          cldep = cdep
+          idum=getdim(cdfilref,cldep,cldepref)   ! look for depth dimension name in ref file
+         IF (cldepref =='unknown' ) cldepref=cdep
+       ELSE 
+          idum=getdim(cdfilref,'depth',cldep   )   ! look for depth dimension name in ref file
+          cldepref=cldep
+       ENDIF
+       cldepvar=cldep
+       istatus = NF90_DEF_DIM(icout,TRIM(cldep),kz, id_z)
+       IF (PRESENT (cdepvar) ) THEN
+         cldepvar=cdepvar
+       ENDIF
+    ENDIF
+
+
+    istatus = NF90_DEF_DIM(icout,'time_counter',NF90_UNLIMITED, id_t)
+
+    nvdim(1) = id_x ; nvdim(2) = id_y ; nvdim(3) = id_z ; nvdim(4) = id_t
+
+    ! Open reference file if any,  otherwise set ncid to flag value (for copy att)
+    IF ( TRIM(cdfilref) /= 'none' ) THEN
+       istatus = NF90_OPEN(cdfilref,NF90_NOWRITE,ncid)
+    ELSE
+       ncid = -9999
+    ENDIF
+
+    ! define variables and copy attributes
+    istatus = NF90_DEF_VAR(icout,'nav_lon',NF90_FLOAT,(/id_x,id_y/),id_lon)
+    istatus = copyatt('nav_lon',id_lon,ncid,icout)
+    istatus = NF90_DEF_VAR(icout,'nav_lat',NF90_FLOAT,(/id_x,id_y/),id_lat)
+    istatus = copyatt('nav_lat',id_lat,ncid,icout)
+    IF ( kz /= 0 ) THEN
+       istatus = NF90_DEF_VAR(icout,TRIM(cldepvar),NF90_FLOAT,(/id_z/),id_dep)
+       ! JMM bug fix : if cdep present, then chose attribute from cldepref
+       istatus = copyatt(TRIM(cldepvar),id_dep,ncid,icout)
+    ENDIF
+
+    istatus = NF90_DEF_VAR(icout,'time_counter',NF90_FLOAT,(/id_t/),id_tim)
+    istatus = copyatt('time_counter',id_tim,ncid,icout)
+
+    istatus = NF90_CLOSE(ncid)
+
+    create=icout
+  END FUNCTION create
+
+  FUNCTION createvar(kout,ptyvar,kvar,kpk, kidvo, cdglobal)
+    !! ----------------------------------------------------------------------------------------------------
+    !!  *** Create kvar n-2D variables cdvar(:), in file id kout, kpk gives the number of vertical levels
+    !!      idvo(:) contains the id of the crated variables.
+    !!     INPUT:
+    !!       kout = ncid of output file
+    !!       cdvar= array of name of variables
+    !!       kvar = number of variables to create
+    !!       kpk  = number of vertical dimensions foreach variable
+    !!
+    !!     OUTPUT:
+    !!       kidvo = arrays with the varid of the variables just created.
+    !!
+    !! ----------------------------------------------------------------------------------------------------
+    ! * Arguments
+    INTEGER, INTENT(in) :: kout, kvar
+    INTEGER, DIMENSION(kvar), INTENT(in) :: kpk
+    INTEGER, DIMENSION(kvar), INTENT(out) :: kidvo
+    INTEGER :: createvar
+    TYPE (variable), DIMENSION(kvar) ,INTENT(in) :: ptyvar
+    CHARACTER(LEN=*), INTENT(in), OPTIONAL :: cdglobal
+
+    ! * Local variables
+    INTEGER :: jv,idims, istatus
+    INTEGER, DIMENSION(4):: iidims
+   
+
+    DO jv = 1, kvar
+
+       ! Create variables whose name is not 'none'
+       IF ( ptyvar(jv)%name /= 'none' ) THEN
+          IF (kpk(jv) == 1 ) THEN
+             idims=3
+             iidims(1) = id_x ; iidims(2) = id_y ; iidims(3) = id_t
+          ELSE IF (kpk(jv) > 1 ) THEN
+             idims=4
+             iidims(1) = id_x ; iidims(2) = id_y ; iidims(3) = id_z ; iidims(4) = id_t
+          ELSE
+             PRINT *,' ERROR: ipk = ',kpk(jv), jv , ptyvar(jv)%name
+             STOP
+          ENDIF
+
+          IF ( ptyvar(jv)%precision == 'r8' ) THEN
+             istatus = NF90_DEF_VAR(kout,ptyvar(jv)%name,NF90_DOUBLE,iidims(1:idims) ,kidvo(jv) )
+          ELSE IF ( ptyvar(jv)%precision == 'i2' ) THEN
+             istatus = NF90_DEF_VAR(kout,ptyvar(jv)%name,NF90_SHORT,iidims(1:idims) ,kidvo(jv) )
+          ELSE IF ( ptyvar(jv)%precision == 'by' ) THEN
+             istatus = NF90_DEF_VAR(kout,ptyvar(jv)%name,NF90_BYTE,iidims(1:idims) ,kidvo(jv) )
+          ELSE
+             IF ( ptyvar(jv)%scale_factor == 1. .AND. ptyvar(jv)%add_offset == 0. ) THEN
+                istatus = NF90_DEF_VAR(kout,ptyvar(jv)%name,NF90_FLOAT,iidims(1:idims) ,kidvo(jv) )
+             ELSE
+                istatus = NF90_DEF_VAR(kout,ptyvar(jv)%name,NF90_SHORT,iidims(1:idims) ,kidvo(jv) )
+             ENDIF
+          ENDIF
+
+          ! add attributes
+          istatus = putatt(ptyvar(jv), kout,kidvo(jv),cdglobal=cdglobal)
+          createvar=istatus
+       ENDIF
+    END DO
+    istatus = NF90_ENDDEF(kout)
+
+  END FUNCTION createvar
+
+  FUNCTION getvarid( cdfile, knvars )
+    !! ------------------------------------------------------------------------------------------
+    !! ***  return a real array with the nvar variable id
+    !!
+    !! ------------------------------------------------------------------------------------------
+    ! * Arguments
+    CHARACTER(LEN=*), INTENT(in) :: cdfile
+    INTEGER, INTENT(in)  ::  knvars                  ! Number of variables in cdfile
+    INTEGER, DIMENSION(knvars) :: getvarid
+
+    !! * local declarations
+    CHARACTER(LEN=256), DIMENSION(knvars) :: cdvar
+    INTEGER :: ncid, jv
+    INTEGER :: istatus
+
+
+    istatus = NF90_OPEN(cdfile,NF90_NOWRITE,ncid)
+    DO jv = 1, knvars
+       istatus = NF90_INQUIRE_VARIABLE(ncid,jv,cdvar(jv) )
+       istatus = NF90_INQ_VARID(ncid,cdvar(jv),getvarid(jv))
+    ENDDO
+    istatus=NF90_CLOSE(ncid)
+
+  END FUNCTION getvarid
+
+  FUNCTION getvaratt (cdfile,cdvar,cdunits, pmissing_value, cdlong_name, cdshort_name)
+    !! ----------------------------------------------------------------------------------------------------
+    !!  ***  Change variable attributs in an existing variable
+    !!
+    !! ----------------------------------------------------------------------------------------------------
+    ! * Arguments
+    CHARACTER(LEN=256), INTENT(in) :: cdfile, cdvar
+    CHARACTER(LEN=256), INTENT(out) :: cdunits, cdlong_name, cdshort_name
+    REAL(KIND=4), INTENT(out) :: pmissing_value
+    INTEGER :: getvaratt
+
+    !! * local declarations
+    INTEGER :: istatus
+    INTEGER :: ncid, varid
+
+    istatus = NF90_OPEN(cdfile,NF90_NOWRITE,ncid)
+    istatus = NF90_INQ_VARID(ncid,cdvar,varid)
+
+    istatus=NF90_GET_ATT(ncid, varid, 'units', cdunits)
+    istatus=NF90_GET_ATT(ncid, varid, '_FillValue', pmissing_value)
+    istatus=NF90_GET_ATT(ncid, varid, 'long_name', cdlong_name)
+    istatus=NF90_GET_ATT(ncid, varid, 'short_name', cdshort_name)
+
+!   istatus = NF90_ENDDEF(ncid)
+    getvaratt=istatus
+    istatus=NF90_CLOSE(ncid)
+
+  END FUNCTION getvaratt
+
+
+  FUNCTION cvaratt (cdfile,cdvar,cdunits,pmissing_value, cdlong_name, cdshort_name)
+    !! ----------------------------------------------------------------------------------------------------
+    !!  ***  Change variable attributs in an existing variable
+    !!
+    !! ----------------------------------------------------------------------------------------------------
+    ! * Arguments
+    CHARACTER(LEN=256), INTENT(in) :: cdfile, cdvar
+    CHARACTER(LEN=256), INTENT(in) :: cdunits, cdlong_name, cdshort_name
+    INTEGER :: cvaratt
+    REAL(KIND=4) :: pmissing_value
+
+    !! * local declarations
+    INTEGER :: istatus
+    INTEGER :: ncid, varid
+
+    istatus = NF90_OPEN(cdfile,NF90_WRITE,ncid)
+    istatus = NF90_REDEF(ncid)
+    istatus = NF90_INQ_VARID(ncid,cdvar,varid)
+
+    istatus=NF90_RENAME_ATT(ncid, varid, 'units', cdunits)
+    istatus=NF90_PUT_ATT(ncid, varid, '_FillValue', pmissing_value)
+    istatus=NF90_RENAME_ATT(ncid, varid, 'long_name', cdlong_name)
+    istatus=NF90_RENAME_ATT(ncid, varid, 'short_name', cdshort_name)
+
+    istatus=NF90_ENDDEF(ncid)
+    cvaratt=istatus
+    istatus=NF90_CLOSE(ncid)
+
+  END FUNCTION cvaratt
+
+
+  FUNCTION putatt (tyvar,kout,kid,cdglobal)
+    !! ----------------------------------------------------------------------------------------------------
+    !!  ***  Scan file att.txt for finding the line corresponding to cdvar, then read the attributes
+    !!       for this variables ,whose id is kid and  write them in file id kout
+    !!
+    !! ----------------------------------------------------------------------------------------------------
+    ! * Arguments
+    INTEGER :: putatt
+    INTEGER, INTENT(in) :: kout, kid
+    TYPE (variable) ,INTENT(in) :: tyvar
+    CHARACTER(LEN=*), INTENT(in), OPTIONAL :: cdglobal !: global attribute
+    putatt=NF90_PUT_ATT(kout,kid,'units',tyvar%units) 
+    IF (putatt /= 0 ) THEN ;PRINT *, NF90_STRERROR(putatt)  ; STOP 'putatt units'; ENDIF
+    putatt=NF90_PUT_ATT(kout,kid,'_FillValue',tyvar%missing_value)  
+    IF (putatt /= 0 ) THEN ;PRINT *, NF90_STRERROR(putatt)  ; STOP 'putatt missing value'; ENDIF
+    putatt=NF90_PUT_ATT(kout,kid,'valid_min',tyvar%valid_min) 
+    IF (putatt /= 0 ) THEN ;PRINT *, NF90_STRERROR(putatt)  ; STOP 'putatt valid_min'; ENDIF
+    putatt=NF90_PUT_ATT(kout,kid,'valid_max',tyvar%valid_max)
+    IF (putatt /= 0 ) THEN ;PRINT *, NF90_STRERROR(putatt)  ; STOP 'putatt valid_max'; ENDIF
+    putatt=NF90_PUT_ATT(kout,kid,'long_name',tyvar%long_name)
+    IF (putatt /= 0 ) THEN ;PRINT *, NF90_STRERROR(putatt)  ; STOP 'putatt longname'; ENDIF
+    putatt=NF90_PUT_ATT(kout,kid,'short_name',tyvar%short_name) 
+    IF (putatt /= 0 ) THEN ;PRINT *, NF90_STRERROR(putatt)  ; STOP 'putatt short name'; ENDIF
+    putatt=NF90_PUT_ATT(kout,kid,'iweight',tyvar%iwght) 
+    IF (putatt /= 0 ) THEN ;PRINT *, NF90_STRERROR(putatt)  ; STOP 'putatt iweight'; ENDIF
+    putatt=NF90_PUT_ATT(kout,kid,'online_operation',tyvar%online_operation) 
+    IF (putatt /= 0 ) THEN ;PRINT *, NF90_STRERROR(putatt)  ; STOP 'putatt online oper'; ENDIF
+    putatt=NF90_PUT_ATT(kout,kid,'axis',tyvar%axis) 
+    IF (putatt /= 0 ) THEN ;PRINT *, NF90_STRERROR(putatt)  ; STOP 'putatt axis'; ENDIF
+    ! Optional attributes (scale_factor, add_offset )
+    putatt=NF90_PUT_ATT(kout,kid,'scale_factor',tyvar%scale_factor) 
+    IF (putatt /= 0 ) THEN ;PRINT *, NF90_STRERROR(putatt)  ; STOP 'putatt scale fact'; ENDIF
+    putatt=NF90_PUT_ATT(kout,kid,'add_offset',tyvar%add_offset) 
+    IF (putatt /= 0 ) THEN ;PRINT *, NF90_STRERROR(putatt)  ; STOP 'putatt add offset'; ENDIF
+    putatt=NF90_PUT_ATT(kout,kid,'savelog10',tyvar%savelog10) 
+    IF (putatt /= 0 ) THEN ;PRINT *, NF90_STRERROR(putatt)  ; STOP 'putatt savelog0'; ENDIF
+    ! Global attribute
+    IF ( PRESENT(cdglobal) ) THEN
+    putatt=NF90_PUT_ATT(kout,NF90_GLOBAL,'history',cdglobal)
+    IF (putatt /= 0 ) THEN ;PRINT *, NF90_STRERROR(putatt)  ; STOP 'putatt global'; ENDIF
+    ENDIF
+
+  END FUNCTION putatt
+
+  FUNCTION getatt(cdfile,cdvar,cdatt)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  getatt  ***
+    !!
+    !! ** Purpose : return a REAL value with the values of the 
+    !!              attribute cdatt for all the variable cdvar  in cdfile
+    !!  
+    !! ** Method : open, read attribute close
+    !!
+    !! history:
+    !!    27/04/2005 : Jean-Marc Molines : Original Code 
+    !!    12/03/2007 :  J.M. Molines : modif 
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+
+    CHARACTER(LEN=*), INTENT(in) :: cdatt,   &   ! attribute name to look for
+         &                          cdfile,  &   ! file to look at
+         &                          cdvar
+
+    REAL(KIND=4) :: getatt
+
+    !! * Local declarations
+
+    INTEGER :: istatus, jv, ncid, idum
+    !! ----------------------------------------------------------
+    istatus=NF90_OPEN(cdfile,NF90_NOWRITE,ncid)
+    istatus=NF90_INQ_VARID(ncid,cdvar,idum)
+    IF ( istatus /= NF90_NOERR) PRINT *, TRIM(NF90_STRERROR(istatus)),' when looking for ',TRIM(cdvar),' in getatt.'
+    istatus = NF90_GET_ATT(ncid, idum,cdatt, getatt)
+    IF ( istatus /= NF90_NOERR ) THEN
+       PRINT *,' getatt problem :',NF90_STRERROR(istatus)
+       PRINT *,' attribute :', TRIM(cdatt)
+       PRINT *,' return default 0 '
+       getatt=0.
+    ENDIF
+    istatus=NF90_CLOSE(ncid)
+
+  END FUNCTION getatt
+
+  FUNCTION  getdim (cdfile,cdim_name,cdtrue,kstatus,ldexact)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  getdim  ***
+    !!
+    !! ** Purpose : return the INTEGER value of the dimension
+    !!              identified with cdim_name in cdfile
+    !!  
+    !! ** Method  : Scan all the dimension name in cdfile and
+    !!              select the one which match cdim_name.
+    !!              cdim_name can be only a fraction of the total name
+    !!              (eg: depth  will be ok for depht, or dephu, or dephv )
+    !!
+    !! history:
+    !!    27/04/2005 : Jean-Marc Molines : Original Code 
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+    CHARACTER(LEN=*), INTENT(in) :: cdfile , &  ! File name to look at
+         &                           cdim_name   ! dimension name to look at
+    CHARACTER(LEN=256),OPTIONAL, INTENT(out) ::  cdtrue ! full name of the read dimension
+    INTEGER, OPTIONAL, INTENT(out) :: kstatus   ! status of the nf inquire
+    LOGICAL, OPTIONAL, INTENT(in) :: ldexact    ! when true look for exact cdim_name
+    INTEGER :: getdim                           ! the value for dim cdim_name, in file cdfile
+
+    ! * Local variables
+    INTEGER :: ncid, id_var
+    INTEGER :: istatus
+    INTEGER :: idims
+    CHARACTER(LEN=256) :: clnam
+    LOGICAL :: lexact=.false.
+    clnam = '-------------'
+
+    IF ( PRESENT(kstatus) ) kstatus=0
+    IF ( PRESENT(ldexact) ) lexact=ldexact
+    istatus=NF90_OPEN(cdfile,NF90_NOWRITE,ncid)
+    IF ( istatus == NF90_NOERR ) THEN
+       istatus=NF90_INQUIRE(ncid,ndimensions=idims)
+
+       id_var = 1
+       ! Look for dim name containing at least 'cdim_name'
+       !     DO WHILE ( INDEX(clnam,cdim_name) == 0 .AND. id_var <= idims )
+       !      istatus=NF90_INQUIRE_DIMENSION(ncid,id_var,name=clnam,len=getdim)
+       !      id_var = id_var + 1
+       !     END DO
+       
+       IF ( (lexact).OR.(trim(cdim_name)=='x').OR.(trim(cdim_name)=='y') ) THEN
+          istatus=NF90_INQ_DIMID(ncid,cdim_name,id_var)
+          IF (istatus /= NF90_NOERR ) THEN
+            PRINT *,NF90_STRERROR(istatus)
+            PRINT *,' Exact dimension name ', TRIM(cdim_name),' not found in ',TRIM(cdfile) ; STOP
+          ENDIF
+          istatus=NF90_INQUIRE_DIMENSION(ncid,id_var,len=getdim)
+          IF ( PRESENT(cdtrue) ) cdtrue=cdim_name
+       ELSE
+          DO id_var = 1,idims
+             istatus=NF90_INQUIRE_DIMENSION(ncid,id_var,name=clnam,len=getdim)
+            IF ( INDEX(clnam,cdim_name) /= 0 ) THEN
+               IF ( PRESENT(cdtrue) ) cdtrue=clnam
+               EXIT
+            ENDIF
+         ENDDO
+       ENDIF
+
+       IF ( id_var > idims ) THEN
+          !      PRINT *,' warning: problem in getdim for ', TRIM(cdim_name),' in ', TRIM(cdfile)
+          IF ( PRESENT(kstatus) ) kstatus=1    ! error send optionally to the calling program
+          getdim=0
+          IF ( PRESENT(cdtrue) ) cdtrue='unknown'
+       ENDIF
+       istatus=NF90_CLOSE(ncid)
+    ELSE
+       IF ( PRESENT(cdtrue) ) cdtrue='unknown'
+       IF ( PRESENT(kstatus) ) kstatus=1 
+    ENDIF
+    ! reset lexact to false for next call 
+    lexact=.false.
+
+  END FUNCTION getdim
+
+  FUNCTION  getspval (cdfile,cdvar)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  getspval  ***
+    !!
+    !! ** Purpose : return the SPVAL value of the variable
+    !!              cdvar  in cdfile
+    !!
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+    CHARACTER(LEN=*), INTENT(in) :: cdfile , &  ! File name to look at
+         &                           cdvar      ! variable name
+    REAL(KIND=4) :: getspval                               ! the missing value for cdvar
+
+    ! * Local variables
+    INTEGER :: ncid, id_var
+    INTEGER :: istatus
+
+    istatus=NF90_OPEN(cdfile,NF90_NOWRITE,ncid)
+    istatus=NF90_INQ_VARID ( ncid,cdvar,id_var)
+    istatus=NF90_GET_ATT(ncid,id_var,"_FillValue",getspval)
+    istatus=NF90_CLOSE(ncid)
+
+  END FUNCTION getspval
+
+  FUNCTION getvdim (cdfile, cdvar)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  getvdim  ***
+    !!
+    !! ** Purpose : return the number of dimensions for variable cdvar in cdfile
+    !!
+    !! ** Method  : Inquire for variable cdvar in cdfile. If found,
+    !!              determines the number of dimensions , assuming that variables
+    !!              are either (x,y,dep,time) or (x,y,time)
+    !!              If cdvar is not found, give an interactive choice for an existing
+    !!              variable, cdvar is then updated to this correct name.
+    !!
+    !! history:
+    !!    31/10/2005 : Jean-Marc Molines : Original Code
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+    CHARACTER(LEN=*), INTENT(in) :: cdfile      ! File name to look at
+    CHARACTER(LEN=*), INTENT(inout) :: cdvar    ! variable name to look at.
+    INTEGER :: getvdim                          ! number of lebvels for cdvar
+
+    !! * Local variables
+    INTEGER :: istatus, ncid, id_var, ivar, idi, istatus0
+    INTEGER :: jvar
+    CHARACTER(LEN=256) :: clongname='long_name', clongn
+
+    CALL ERR_HDL(NF90_OPEN(cdfile,NF90_NOWRITE,ncid))
+    istatus0 = NF90_INQ_VARID ( ncid,cdvar,id_var)
+    DO WHILE  ( istatus0 == NF90_ENOTVAR ) 
+       ivar=getnvar(cdfile)
+       PRINT *, 'Give the number corresponding to the variable you want to work with '
+       DO jvar = 1, ivar
+          clongn=''
+          istatus=NF90_INQUIRE_VARIABLE (ncid, jvar, cdvar,ndims=idi)
+          istatus=NF90_GET_ATT (ncid,jvar,clongname,clongn)
+          IF (istatus /= NF90_NOERR ) clongn='unknown'
+          PRINT *, jvar, ' ',TRIM(cdvar),' ',TRIM(clongn)
+       ENDDO
+       READ *,id_var
+       istatus0=NF90_INQUIRE_VARIABLE (ncid, id_var, cdvar,ndims=idi)
+    ENDDO
+    ! 
+    CALL ERR_HDL(NF90_INQUIRE_VARIABLE (ncid, id_var, cdvar,ndims=idi))
+    getvdim=idi-1
+    CALL ERR_HDL (NF90_CLOSE(ncid))
+  END FUNCTION getvdim
+
+  FUNCTION  getnvar (cdfile)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  getnvar  ***
+    !!
+    !! ** Purpose : return the number of variables in cdfile
+    !!
+    !! ** Method  :
+    !!
+    !! history:
+    !!    27/04/2005 : Jean-Marc Molines : Original Code
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+    CHARACTER(LEN=*), INTENT(in) ::  cdfile   ! file to look at
+    INTEGER :: getnvar                        ! return the number of variables
+
+    !! * Local variables
+    INTEGER :: ncid
+    INTEGER :: istatus
+
+    istatus=NF90_OPEN(cdfile,NF90_NOWRITE,ncid)
+    istatus=NF90_INQUIRE(ncid,nvariables= getnvar)
+    istatus=NF90_CLOSE(ncid)
+
+  END FUNCTION getnvar
+
+  FUNCTION  getipk (cdfile,knvars,cdep)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  getipk  ***
+    !!
+    !! ** Purpose : return the number of levels for all the variables
+    !!              in cdfile. Return 0 if the variable in a vector.
+    !!
+    !! ** Method  : returns npk when 4D variables ( x,y,z,t )
+    !!              returns  1  when 3D variables ( x,y,  t )
+    !!              returns  0  when other ( vectors )
+    !!
+    !! history:
+    !!    27/04/2005 : Jean-Marc Molines : Original Code
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+    CHARACTER(LEN=*), INTENT(in) :: cdfile   ! File to look at
+    INTEGER, INTENT(in)  ::  knvars          ! Number of variables in cdfile
+    CHARACTER(LEN=*), OPTIONAL, INTENT(in) :: cdep ! optional depth dim name
+    INTEGER, DIMENSION(knvars) :: getipk     ! array (variables ) of levels
+
+    !! * local declarations
+    INTEGER :: ncid, ipk, jv, iipk
+    INTEGER :: istatus
+    CHARACTER(LEN=256) :: cldep='dep'
+
+
+    istatus=NF90_OPEN(cdfile,NF90_NOWRITE,ncid)
+    IF (  PRESENT (cdep) ) cldep = cdep
+    ! Note the very important TRIM below : if not, getdim crashes as it never find the correct dim !
+    iipk = getdim(cdfile,TRIM(cldep),kstatus=istatus)
+    IF ( istatus /= 0 ) THEN
+       PRINT *,' getipk : vertical dim not found ...assume 1'
+       iipk=1
+    ENDIF
+    DO jv = 1, knvars
+       istatus=NF90_INQUIRE_VARIABLE(ncid,jv, ndims=ipk)
+       IF (ipk == 4 ) THEN
+          getipk(jv) = iipk
+       ELSE IF (ipk == 3 ) THEN
+          getipk(jv) = 1
+       ELSE
+          getipk(jv) = 0
+       ENDIF
+    END DO
+    istatus=NF90_CLOSE(ncid)
+
+  END FUNCTION getipk
+
+  FUNCTION  getvarname (cdfile, knvars, ptypvar)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  getvarname  ***
+    !!
+    !! ** Purpose : return a character array with the knvars variable
+    !!              name corresponding to cdfile
+    !!
+    !! ** Method  : 
+    !!
+    !!
+    !! history:
+    !!    27/04/2005 : Jean-Marc Molines : Original Code
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+    CHARACTER(LEN=*), INTENT(in) :: cdfile
+    INTEGER, INTENT(in)  ::  knvars                  ! Number of variables in cdfile
+    CHARACTER(LEN=256), DIMENSION(knvars) :: getvarname
+    TYPE (variable), DIMENSION (knvars) :: ptypvar  ! Retrieve variables attribute
+
+    !! * local declarations
+    INTEGER :: ncid,  jv, ILEN
+    INTEGER :: istatus
+    CHARACTER(LEN=256) :: cldum=''
+    REAL(KIND=4) :: zatt
+    INTEGER      :: iatt
+
+    istatus=NF90_OPEN(cdfile,NF90_NOWRITE,ncid)
+    DO jv = 1, knvars
+       istatus=NF90_INQUIRE_VARIABLE(ncid,jv,name=getvarname(jv) )
+       ptypvar(jv)%name=getvarname(jv)
+       ! look for standard attibutes
+       IF ( NF90_INQUIRE_ATTRIBUTE(ncid,jv,'units',len=ILEN) == NF90_NOERR ) THEN
+          istatus=NF90_GET_ATT(ncid,jv,'units',cldum(1:ILEN))
+          ptypvar(jv)%units=TRIM(cldum)
+          cldum =''
+       ELSE 
+          ptypvar(jv)%units='N/A'
+       ENDIF
+
+       IF ( NF90_INQUIRE_ATTRIBUTE(ncid,jv,'_FillValue') == NF90_NOERR ) THEN
+          istatus=NF90_GET_ATT(ncid,jv,'_FillValue',zatt)
+          ptypvar(jv)%missing_value=zatt
+       ELSE 
+          ptypvar(jv)%missing_value=0.
+       ENDIF
+
+       IF ( NF90_INQUIRE_ATTRIBUTE(ncid,jv,'valid_min') == NF90_NOERR ) THEN
+          istatus=NF90_GET_ATT(ncid,jv,'valid_min',zatt)
+          ptypvar(jv)%valid_min=zatt
+       ELSE
+          ptypvar(jv)%valid_min=0.
+       ENDIF
+
+       IF ( NF90_INQUIRE_ATTRIBUTE(ncid,jv,'valid_max') == NF90_NOERR ) THEN
+          istatus=NF90_GET_ATT(ncid,jv,'valid_max',zatt)
+          ptypvar(jv)%valid_max=zatt
+       ELSE
+          ptypvar(jv)%valid_max=0.
+       ENDIF
+
+       IF ( NF90_INQUIRE_ATTRIBUTE(ncid,jv,'iweight') == NF90_NOERR ) THEN
+          istatus=NF90_GET_ATT(ncid,jv,'iweight',iatt)
+          ptypvar(jv)%iwght=iatt
+       ELSE
+          ptypvar(jv)%iwght=1
+       ENDIF
+
+       IF ( NF90_INQUIRE_ATTRIBUTE(ncid,jv,'long_name',len=ILEN) == NF90_NOERR ) THEN
+          istatus=NF90_GET_ATT(ncid,jv,'long_name',cldum(1:ILEN))
+          ptypvar(jv)%long_name=TRIM(cldum)
+          cldum=''
+       ELSE
+          ptypvar(jv)%long_name='N/A'
+       ENDIF
+
+       IF ( NF90_INQUIRE_ATTRIBUTE(ncid,jv,'short_name',len=ILEN) == NF90_NOERR ) THEN
+          istatus=NF90_GET_ATT(ncid,jv,'short_name',cldum(1:ILEN))
+          ptypvar(jv)%short_name=TRIM(cldum)
+          cldum=''
+       ELSE
+          ptypvar(jv)%short_name='N/A'
+       ENDIF
+
+       IF ( NF90_INQUIRE_ATTRIBUTE(ncid,jv,'online_operation',len=ILEN) == NF90_NOERR ) THEN
+          istatus=NF90_GET_ATT(ncid,jv,'online_operation',cldum(1:ILEN))
+          ptypvar(jv)%online_operation=TRIM(cldum)
+          cldum=''
+       ELSE
+          ptypvar(jv)%online_operation='N/A'
+       ENDIF
+
+       IF ( NF90_INQUIRE_ATTRIBUTE(ncid,jv,'axis',len=ILEN) == NF90_NOERR ) THEN
+          istatus=NF90_GET_ATT(ncid,jv,'axis',cldum(1:ILEN))
+          ptypvar(jv)%axis=TRIM(cldum)
+          cldum=''
+       ELSE
+          ptypvar(jv)%axis='N/A'
+       ENDIF
+
+    END DO
+    istatus=NF90_CLOSE(ncid)
+
+  END FUNCTION getvarname
+
+  FUNCTION  getvar (cdfile,cdvar,klev,kpi,kpj,kimin,kjmin, ktime,ldiom)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  getvar  ***
+    !!
+    !! ** Purpose : Return the 2D REAL variable cvar, from cdfile at level klev.
+    !!              kpi,kpj are the horizontal size of the 2D variable
+    !!
+    !! ** Method  :
+    !!
+    !!
+    !! history:
+    !!    27/04/2005 : Jean-Marc Molines : Original Code
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+    CHARACTER(LEN=*), INTENT(in) :: cdfile,     &   ! file name to work with
+         &                          cdvar           ! variable name to work with
+    INTEGER, INTENT(in) :: kpi,kpj                  ! horizontal size of the 2D variable
+    INTEGER, OPTIONAL, INTENT(in) :: klev           ! Optional variable. If missing 1 is assumed
+    INTEGER, OPTIONAL, INTENT(in) :: kimin,kjmin    ! Optional variable. If missing 1 is assumed
+    INTEGER, OPTIONAL, INTENT(in) :: ktime          ! Optional variable. If missing 1 is assumed
+    LOGICAL, OPTIONAL, INTENT(in) :: ldiom          ! Optional variable. If missing false is assumed
+    REAL(KIND=4), DIMENSION(kpi,kpj) :: getvar      ! 2D REAL 4 holding variable field at klev
+
+    !! * Local variables
+    INTEGER, DIMENSION(4) :: istart, icount, nldim
+    INTEGER :: ncid, id_var, id_dimunlim, nbdim
+    INTEGER :: istatus, ilev, imin, jmin, itime, ilog, ipiglo, imax
+    INTEGER, SAVE :: ii, ij, ik0, ji, jj, ik1, ik
+    LOGICAL :: lliom=.false., llperio=.false.
+    CHARACTER(LEN=256) :: clvar
+
+    LOGICAL :: llog=.FALSE. , lsf=.FALSE. , lao=.FALSE.
+    REAL(KIND=4) :: sf=1., ao=0.        !: Scale factor and add_offset
+    REAL(KIND=4) :: spval               !: missing value
+    REAL(KIND=4) , DIMENSION (:,:), ALLOCATABLE :: zend, zstart
+
+    llperio=.false.
+    IF (PRESENT(klev) ) THEN
+       ilev=klev
+    ELSE
+       ilev=1
+    ENDIF
+
+    IF (PRESENT(kimin) ) THEN
+       imin=kimin
+       ! next line in problem when x_a is before x in the mesh files ...
+       ipiglo=getdim(cdfile,'x',ldexact=.true.)
+       IF (imin+kpi-1 > ipiglo ) THEN 
+         llperio=.true.
+         imax=kpi+1 +imin -ipiglo
+       ENDIF
+    ELSE
+       imin=1
+    ENDIF
+
+    IF (PRESENT(kjmin) ) THEN
+       jmin=kjmin
+    ELSE
+       jmin=1
+    ENDIF
+
+    IF (PRESENT(ktime) ) THEN
+       itime=ktime
+    ELSE
+       itime=1
+    ENDIF
+
+    IF (PRESENT(ldiom) ) THEN
+       lliom=ldiom
+    ELSE
+       lliom=.false.
+    ENDIF
+
+    clvar=cdvar
+
+    ! Must reset the flags to false for every call to getvar
+    llog=.FALSE.
+    lsf=.FALSE.
+    lao=.FALSE.
+
+    CALL ERR_HDL(NF90_OPEN(cdfile,NF90_NOWRITE,ncid) )
+    IF ( lliom) THEN  ! try to detect if input file is a zgr IOM file, looking for e3t_0
+      istatus=NF90_INQ_VARID( ncid,'e3t_0', id_var)
+      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( ncid,'e3t_ps', id_var)
+         IF ( istatus == NF90_NOERR ) THEN  
+           ! case of NEMO_v3 zfr files
+           ! look for mbathy and out it in memory, once for all
+           IF ( .NOT. l_mbathy ) THEN
+             PRINT *,'MESH_ZGR V3 detected'
+             l_mbathy=.true.
+             istatus=NF90_INQ_DIMID(ncid,'x',id_var) ; istatus=NF90_INQUIRE_DIMENSION(ncid,id_var,len=ii)
+             istatus=NF90_INQ_DIMID(ncid,'y',id_var) ; istatus=NF90_INQUIRE_DIMENSION(ncid,id_var,len=ij)
+             istatus=NF90_INQ_DIMID(ncid,'z',id_var) ; istatus=NF90_INQUIRE_DIMENSION(ncid,id_var,len=ik0)
+             ALLOCATE( mbathy(ii,ij))               ! mbathy is allocated on the whole domain
+             ALLOCATE( e3t_ps(ii,ij),e3w_ps(ii,ij)) ! e3._ps  are  allocated on the whole domain
+             ALLOCATE( e3t_0(ik0), e3w_0(ik0) )       ! whole depth
+
+             istatus=NF90_INQ_VARID (ncid,'mbathy', id_var)
+             IF ( istatus /=  NF90_NOERR ) THEN
+               PRINT *, 'Problem reading mesh_zgr.nc v3 : no mbathy found !' ; STOP
+             ENDIF
+             istatus=NF90_GET_VAR(ncid,id_var,mbathy, start=(/1,1,1/), count=(/ii,ij,1/) )
+             !
+             istatus=NF90_INQ_VARID (ncid,'e3t_ps', id_var)
+             IF ( istatus /=  NF90_NOERR ) THEN
+               PRINT *, 'Problem reading mesh_zgr.nc v3 : no e3t_ps found !' ; STOP
+             ENDIF
+             istatus=NF90_GET_VAR(ncid,id_var,e3t_ps, start=(/1,1,1/), count=(/ii,ij,1/) )
+             !
+             istatus=NF90_INQ_VARID (ncid,'e3w_ps', id_var)
+             IF ( istatus /=  NF90_NOERR ) THEN
+               PRINT *, 'Problem reading mesh_zgr.nc v3 : no e3w_ps found !' ; STOP
+             ENDIF
+             istatus=NF90_GET_VAR(ncid,id_var,e3w_ps, start=(/1,1,1/), count=(/ii,ij,1/) )
+             !
+             istatus=NF90_INQ_VARID (ncid,'e3t_0', id_var)
+             IF ( istatus /=  NF90_NOERR ) THEN
+               PRINT *, 'Problem reading mesh_zgr.nc v3 : no e3t_0 found !' ; STOP
+             ENDIF
+             istatus=NF90_GET_VAR(ncid,id_var,e3t_0, start=(/1,1/), count=(/ik0,1/) )
+             !
+             istatus=NF90_INQ_VARID (ncid,'e3w_0', id_var)
+             IF ( istatus /=  NF90_NOERR ) THEN
+               PRINT *, 'Problem reading mesh_zgr.nc v3 : no e3w_0 found !' ; STOP
+             ENDIF
+             istatus=NF90_GET_VAR(ncid,id_var,e3w_0, start=(/1,1/), count=(/ik0,1/) )
+             DO ji=1,ii
+                DO jj=1,ij
+                   IF ( e3t_ps (ji,jj) == 0 ) e3t_ps(ji,jj)=e3t_0(mbathy(ji,jj))
+                END DO
+             END DO
+           ENDIF
+          ! zgr v3
+          SELECT CASE ( clvar )
+           CASE ('e3u_ps')  ; clvar='e3t_ps'
+           CASE ('e3v_ps')  ; clvar='e3t_ps'
+           CASE ('e3w_ps')  ; clvar='e3w_ps'
+          END SELECT
+         ELSE
+          ! zgr v2
+          SELECT CASE ( clvar )
+           CASE ('e3t_ps')  ; clvar='e3t'
+           CASE ('e3u_ps')  ; clvar='e3u'
+           CASE ('e3v_ps')  ; clvar='e3v'
+           CASE ('e3w_ps')  ; clvar='e3w'
+          END SELECT
+         ENDIF
+      ENDIF
+    ENDIF
+
+    istatus=NF90_INQUIRE(ncid,unlimitedDimId=id_dimunlim)
+    CALL ERR_HDL(NF90_INQ_VARID ( ncid,clvar,id_var))
+    ! look for time dim in variable
+    nldim=0
+    istatus=NF90_INQUIRE_VARIABLE(ncid, id_var,ndims=nbdim,dimids=nldim(:) )
+
+    istart(1) = imin
+    istart(2) = jmin
+    ! JMM ! it workd for X Y Z T file,   not for X Y T .... try to found a fix !
+    IF ( nldim(3) == id_dimunlim ) THEN
+    istart(3) = itime
+    istart(4) = 1
+    ELSE
+    istart(3) = ilev
+    istart(4) = itime
+    ENDIF
+
+    icount(1)=kpi
+    icount(2)=kpj
+    icount(3)=1
+    icount(4)=1
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(ncid,id_var,'_FillValue')
+    IF (istatus == NF90_NOERR ) THEN
+       istatus=NF90_GET_ATT(ncid,id_var,'_FillValue',spval)
+    ELSE
+       ! assume spval is 0 ?
+       spval = 0.
+    ENDIF
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(ncid,id_var,'savelog10')
+    IF (istatus == NF90_NOERR ) THEN
+       ! there is a scale factor for this variable
+       istatus=NF90_GET_ATT(ncid,id_var,'savelog10',ilog)
+       IF ( ilog /= 0 ) llog=.TRUE.
+    ENDIF
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(ncid,id_var,'scale_factor')
+    IF (istatus == NF90_NOERR ) THEN
+       ! there is a scale factor for this variable
+       istatus=NF90_GET_ATT(ncid,id_var,'scale_factor',sf)
+       IF ( sf /= 1. ) lsf=.TRUE.
+    ENDIF
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(ncid,id_var,'add_offset')
+    IF (istatus == NF90_NOERR ) THEN
+       ! there is a scale factor for this variable
+       istatus=NF90_GET_ATT(ncid,id_var,'add_offset',ao)
+       IF ( ao /= 0.) lao=.TRUE.
+    ENDIF
+
+
+    IF (llperio ) THEN
+      ALLOCATE (zend (ipiglo-imin,kpj), zstart(imax-1,kpj) )
+      IF (l_mbathy .AND. &
+        &  ( cdvar == 'e3t_ps' .OR. cdvar == 'e3w_ps' .OR. cdvar == 'e3u_ps' .OR. cdvar == 'e3v_ps'))  THEN
+       istatus=0
+       clvar=cdvar
+       SELECT CASE ( clvar )
+         CASE ( 'e3t_ps', 'e3u_ps', 'e3v_ps' ) 
+           DO ji=1,ipiglo-imin
+            DO jj=1,kpj
+             ik=mbathy(imin+ji-1, jmin+jj-1)
+             IF (ilev == ik ) THEN
+               zend(ji,jj)=e3t_ps(imin+ji-1, jmin+jj-1)
+             ELSE
+               zend(ji,jj)=e3t_0(ilev)
+             ENDIF
+            END DO
+           END DO
+           DO ji=1,imax-1
+            DO jj=1,kpj
+             ik=mbathy(ji+1, jmin+jj-1)
+             IF (ilev == ik ) THEN
+               zstart(ji,jj)=e3t_ps(ji+1, jmin+jj-1)
+             ELSE
+               zstart(ji,jj)=e3t_0(ilev)
+             ENDIF
+            END DO
+           END DO
+          getvar(1:ipiglo-imin,:)=zend
+          getvar(ipiglo-imin+1:kpi,:)=zstart
+         IF (clvar == 'e3u_ps') THEN
+         DO ji=1,kpi-1
+          DO jj=1,kpj
+            getvar(ji,jj)=MIN(getvar(ji,jj),getvar(ji+1,jj))
+          END DO
+         END DO
+           ! not very satisfactory but still....
+           getvar(kpi,:)=getvar(kpi-1,:)
+         ENDIF
+
+         IF (clvar == 'e3v_ps') THEN
+         DO ji=1,kpi
+          DO jj=1,kpj-1
+            getvar(ji,jj)=MIN(getvar(ji,jj),getvar(ji,jj+1))
+          END DO
+         END DO
+           ! not very satisfactory but still....
+           getvar(:,kpj)=getvar(:,kpj-1)
+         ENDIF
+         
+         CASE ( 'e3w_ps')
+           DO ji=1,ipiglo-imin
+            DO jj=1,kpj
+             ik=mbathy(imin+ji-1, jmin+jj-1)
+             IF (ilev == ik ) THEN
+               zend(ji,jj)=e3w_ps(imin+ji-1, jmin+jj-1)
+             ELSE
+               zend(ji,jj)=e3w_0(ilev)
+             ENDIF
+            END DO
+           END DO
+           DO ji=1,imax-1
+            DO jj=1,kpj
+             ik=mbathy(ji+1, jmin+jj-1)
+             IF (ilev == ik ) THEN
+               zstart(ji,jj)=e3w_ps(ji+1, jmin+jj-1)
+             ELSE
+               zstart(ji,jj)=e3w_0(ilev)
+             ENDIF
+            END DO
+           END DO
+       getvar(1:ipiglo-imin,:)=zend
+       getvar(ipiglo-imin+1:kpi,:)=zstart
+
+       END SELECT
+      ELSE
+       istatus=NF90_GET_VAR(ncid,id_var,zend, start=(/imin,jmin,ilev,itime/),count=(/ipiglo-imin,kpj,1,1/))
+       istatus=NF90_GET_VAR(ncid,id_var,zstart, start=(/2,jmin,ilev,itime/),count=(/imax-1,kpj,1,1/))
+       getvar(1:ipiglo-imin,:)=zend
+       getvar(ipiglo-imin+1:kpi,:)=zstart
+      ENDIF
+      DEALLOCATE(zstart, zend )
+    ELSE
+      IF (l_mbathy .AND. &
+        &  ( cdvar == 'e3t_ps' .OR. cdvar == 'e3w_ps' .OR. cdvar == 'e3u_ps' .OR. cdvar == 'e3v_ps'))  THEN
+       istatus=0
+       clvar=cdvar
+       SELECT CASE ( clvar )
+         CASE ( 'e3t_ps', 'e3u_ps', 'e3v_ps' ) 
+         DO ji=1,kpi
+          DO jj=1,kpj
+           ik=mbathy(imin+ji-1, jmin+jj-1)
+           IF (ilev == ik ) THEN
+             getvar(ji,jj)=e3t_ps(imin+ji-1, jmin+jj-1)
+           ELSE
+             getvar(ji,jj)=e3t_0(ilev)
+           ENDIF
+          END DO
+         END DO
+         IF (clvar == 'e3u_ps') THEN
+         DO ji=1,kpi-1
+          DO jj=1,kpj
+            getvar(ji,jj)=MIN(getvar(ji,jj),getvar(ji+1,jj))
+          END DO
+         END DO
+           ! not very satisfactory but still....
+           getvar(kpi,:)=getvar(2,:) 
+         ENDIF
+         IF (clvar == 'e3v_ps') THEN
+         DO ji=1,kpi
+          DO jj=1,kpj-1
+            getvar(ji,jj)=MIN(getvar(ji,jj),getvar(ji,jj+1))
+          END DO
+         END DO
+           ! not very satisfactory but still....
+           getvar(:,kpj)=getvar(:,kpj-1)
+         ENDIF
+
+         CASE ( 'e3w_ps')
+         DO ji=1,kpi
+          DO jj=1,kpj
+           ik=mbathy(imin+ji-1, jmin+jj-1)
+           IF (ilev == ik ) THEN
+             getvar(ji,jj)=e3w_ps(imin+ji-1, jmin+jj-1)
+           ELSE
+             getvar(ji,jj)=e3w_0(ilev)
+           ENDIF
+          END DO
+         END DO
+
+       END SELECT
+      ELSE
+        istatus=NF90_GET_VAR(ncid,id_var,getvar, start=istart,count=icount)
+      ENDIF
+    ENDIF
+    IF ( istatus /= 0 ) THEN
+       PRINT *,' Problem in getvar for ', TRIM(clvar)
+       CALL ERR_HDL(istatus)
+       STOP
+    ENDIF
+
+    ! Caution : order does matter !
+    IF (lsf )  WHERE (getvar /= spval )  getvar=getvar*sf
+    IF (lao )  WHERE (getvar /= spval )  getvar=getvar + ao
+    IF (llog)  WHERE (getvar /= spval )  getvar=10**getvar
+
+    istatus=NF90_CLOSE(ncid)
+
+  END FUNCTION getvar
+
+  FUNCTION  getvarxz (cdfile,cdvar,kj,kpi,kpz,kimin,kkmin,ktime)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  getvar  ***
+    !!
+    !! ** Purpose : Return the 2D REAL variable x-z slab cvar, from cdfile at j=kj
+    !!              kpi,kpz are the  size of the 2D variable
+    !!
+    !! ** Method  :
+    !!
+    !! history:
+    !!    03/03/2006 : Jean-Marc Molines : Original code
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+    CHARACTER(LEN=*), INTENT(in) :: cdfile,     &   ! file name to work with
+         &                          cdvar           ! variable name to work with
+    INTEGER, INTENT(in) :: kpi,kpz                  ! size of the 2D variable
+    INTEGER, INTENT(in) :: kj                       ! Optional variable. If missing 1 is assumed
+    INTEGER, OPTIONAL, INTENT(in) :: kimin,kkmin    ! Optional variable. If missing 1 is assumed
+    INTEGER, OPTIONAL, INTENT(in) :: ktime          ! Optional variable. If missing 1 is assumed 
+    REAL(KIND=4), DIMENSION(kpi,kpz) :: getvarxz    ! 2D REAL 4 holding variable x-z slab at kj
+
+    !! * Local variables
+    INTEGER, DIMENSION(4) :: istart, icount
+    INTEGER :: ncid, id_var
+    INTEGER :: istatus, ilev, imin, kmin,  itime, ilog
+
+    LOGICAL :: llog=.FALSE. , lsf=.FALSE. , lao=.FALSE.
+    REAL(KIND=4) :: sf=1., ao=0.        !: Scale factor and add_offset
+    REAL(KIND=4)         :: spval       !: Missing values
+
+
+    IF (PRESENT(kimin) ) THEN
+       imin=kimin
+    ELSE
+       imin=1
+    ENDIF
+
+    IF (PRESENT(kkmin) ) THEN
+       kmin=kkmin
+    ELSE
+       kmin=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.
+
+    istart(1) = imin
+    istart(2) = kj
+    istart(3) = kmin
+    ! JMM ! it workd for X Y Z T file,   not for X Y T .... try to found a fix !
+    istart(4) = itime
+
+    icount(1)=kpi
+    icount(2)=1
+    icount(3)=kpz
+    icount(4)=1
+
+    CALL ERR_HDL(NF90_OPEN(cdfile,NF90_NOWRITE,ncid) )
+    CALL ERR_HDL(NF90_INQ_VARID ( ncid,cdvar,id_var))
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(ncid,id_var,'_FillValue')
+    IF (istatus == NF90_NOERR ) THEN
+       istatus=NF90_GET_ATT(ncid,id_var,'_FillValue',spval)
+    ELSE
+       ! assume spval is 0 ?
+       spval = 0.
+    ENDIF
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(ncid,id_var,'savelog10')
+    IF (istatus == NF90_NOERR ) THEN
+       ! there is a scale factor for this variable
+       istatus=NF90_GET_ATT(ncid,id_var,'savelog10',ilog)
+       IF ( ilog /= 0 ) llog=.TRUE.
+    ENDIF
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(ncid,id_var,'scale_factor')
+    IF (istatus == NF90_NOERR ) THEN
+       ! there is a scale factor for this variable
+       istatus=NF90_GET_ATT(ncid,id_var,'scale_factor',sf)
+       IF ( sf /= 1. ) lsf=.TRUE.
+    ENDIF
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(ncid,id_var,'add_offset')
+    IF (istatus == NF90_NOERR ) THEN
+       ! there is a scale factor for this variable
+       istatus=NF90_GET_ATT(ncid,id_var,'add_offset',ao)
+       IF ( ao /= 0.) lao=.TRUE.
+    ENDIF
+
+    istatus=NF90_GET_VAR(ncid,id_var,getvarxz, start=istart,count=icount)
+    IF ( istatus /= 0 ) THEN
+       PRINT *,' Problem in getvarxz for ', TRIM(cdvar)
+       CALL ERR_HDL(istatus)
+       STOP
+    ENDIF
+
+    ! Caution : order does matter !
+    IF (lsf )  WHERE (getvarxz /= spval )  getvarxz=getvarxz*sf
+    IF (lao )  WHERE (getvarxz /= spval )  getvarxz=getvarxz + ao
+    IF (llog)  WHERE (getvarxz /= spval )  getvarxz=10**getvarxz
+
+    istatus=NF90_CLOSE(ncid)
+
+  END FUNCTION getvarxz
+
+  FUNCTION  getvaryz (cdfile,cdvar,ki,kpj,kpz,kjmin,kkmin,ktime)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  getvar  ***
+    !!
+    !! ** Purpose : Return the 2D REAL variable y-z slab cvar, from cdfile at i=ki
+    !!              kpj,kpz are the  size of the 2D variable
+    !!
+    !! ** Method  :
+    !!
+    !! history:
+    !!    03/03/2006 : Jean-Marc Molines : Original code
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+    CHARACTER(LEN=*), INTENT(in) :: cdfile,     &   ! file name to work with
+         &                          cdvar           ! variable name to work with
+    INTEGER, INTENT(in) :: kpj,kpz                  ! size of the 2D variable
+    INTEGER, INTENT(in) :: ki                       ! 
+    INTEGER, OPTIONAL, INTENT(in) :: kjmin,kkmin    ! Optional variable. If missing 1 is assumed
+    INTEGER, OPTIONAL, INTENT(in) :: ktime          ! Optional variable. If missing 1 is assumed
+    REAL(KIND=4), DIMENSION(kpj,kpz) :: getvaryz    ! 2D REAL 4 holding variable x-z slab at kj
+
+    !! * Local variables
+    INTEGER, DIMENSION(4) :: istart, icount
+    INTEGER :: ncid, id_var
+    INTEGER :: istatus, ilev, jmin, kmin, itime, ilog
+
+    LOGICAL :: llog=.FALSE. , lsf=.FALSE. , lao=.FALSE.
+    REAL(KIND=4) :: sf=1., ao=0.        !: Scale factor and add_offset
+    REAL(KIND=4)         :: spval       !: Missing values
+
+    IF (PRESENT(kjmin) ) THEN
+       jmin=kjmin
+    ELSE
+       jmin=1
+    ENDIF
+
+    IF (PRESENT(kkmin) ) THEN
+       kmin=kkmin
+    ELSE
+       kmin=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.
+
+    istart(1) = ki
+    istart(2) = jmin
+    istart(3) = kmin
+    istart(4) = 1
+
+    icount(1)=1
+    icount(2)=kpj
+    icount(3)=kpz
+    ! JMM ! it workd for X Y Z T file,   not for X Y T .... try to found a fix !
+    icount(4)=itime
+
+    CALL ERR_HDL(NF90_OPEN(cdfile,NF90_NOWRITE,ncid) )
+    CALL ERR_HDL(NF90_INQ_VARID ( ncid,cdvar,id_var))
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(ncid,id_var,'_FillValue')
+    IF (istatus == NF90_NOERR ) THEN
+       istatus=NF90_GET_ATT(ncid,id_var,'_FillValue',spval)
+    ELSE
+       ! assume spval is 0 ?
+       spval = 0.
+    ENDIF
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(ncid,id_var,'savelog10')
+    IF (istatus == NF90_NOERR ) THEN
+       ! there is a scale factor for this variable
+       istatus=NF90_GET_ATT(ncid,id_var,'savelog10',ilog)
+       IF ( ilog /= 0 ) llog=.TRUE.
+    ENDIF
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(ncid,id_var,'scale_factor')
+    IF (istatus == NF90_NOERR ) THEN
+       ! there is a scale factor for this variable
+       istatus=NF90_GET_ATT(ncid,id_var,'scale_factor',sf)
+       IF ( sf /= 1. ) lsf=.TRUE.
+    ENDIF
+
+    istatus=NF90_INQUIRE_ATTRIBUTE(ncid,id_var,'add_offset')
+    IF (istatus == NF90_NOERR ) THEN
+       ! there is a scale factor for this variable
+       istatus=NF90_GET_ATT(ncid,id_var,'add_offset',ao)
+       IF ( ao /= 0.) lao=.TRUE.
+    ENDIF
+
+    istatus=NF90_GET_VAR(ncid,id_var,getvaryz, start=istart,count=icount)
+    IF ( istatus /= 0 ) THEN
+       PRINT *,' Problem in getvaryz for ', TRIM(cdvar)
+       CALL ERR_HDL(istatus)
+       STOP
+    ENDIF
+
+    ! Caution : order does matter !
+    IF (lsf )  WHERE (getvaryz /= spval )  getvaryz=getvaryz*sf
+    IF (lao )  WHERE (getvaryz /= spval )  getvaryz=getvaryz + ao
+    IF (llog)  WHERE (getvaryz /= spval )  getvaryz=10**getvaryz
+
+    istatus=NF90_CLOSE(ncid)
+
+  END FUNCTION getvaryz
+
+  FUNCTION  getvar1d (cdfile,cdvar,kk,kstatus)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  getvar1d  ***
+    !!
+    !! ** Purpose :  return 1D variable cdvar from cdfile, of size kk
+    !!
+    !! ** Method  :
+    !!
+    !!
+    !! history:
+    !!    27/04/2005 : Jean-Marc Molines : Original Code
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+    CHARACTER(LEN=*), INTENT(in) :: cdfile,     &   ! file name to work with
+         &                          cdvar           ! variable name to work with
+    INTEGER, INTENT(in) :: kk                       ! size of 1D vector to be returned
+    INTEGER, OPTIONAL, INTENT(out) :: kstatus       ! return status concerning the variable existence
+    REAL(KIND=4), DIMENSION(kk) :: getvar1d         ! real returned vector
+
+    !! * Local variables
+    INTEGER, DIMENSION(1) :: istart, icount
+    INTEGER :: ncid, id_var
+    INTEGER :: istatus
+
+    istart(:) = 1
+    icount(1)=kk
+    IF ( PRESENT(kstatus) ) kstatus = 0
+
+    istatus=NF90_OPEN(cdfile,NF90_NOWRITE,ncid)
+    istatus=NF90_INQ_VARID ( ncid,cdvar,id_var)
+    IF ( istatus == NF90_NOERR ) THEN
+       istatus=NF90_GET_VAR(ncid,id_var,getvar1d,start=istart,count=icount)
+    ELSE
+       IF ( PRESENT(kstatus) ) kstatus= istatus
+       getvar1d=99999999999.
+    ENDIF
+
+    istatus=NF90_CLOSE(ncid)
+
+  END FUNCTION getvar1d
+
+  FUNCTION  getvare3 (cdfile,cdvar,kk)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  getvare3  ***
+    !!
+    !! ** Purpose :  Special routine for e3, which in fact is a 1D variable
+    !!               but defined as e3 (1,1,npk,1) in coordinates.nc (!!)
+    !!
+    !! ** Method  :
+    !!
+    !!
+    !! history:
+    !!    27/04/2005 : Jean-Marc Molines : Original Code
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+    CHARACTER(LEN=*), INTENT(in) :: cdfile,     &   ! file name to work with
+         &                          cdvar           ! variable name to work with
+    INTEGER, INTENT(in) :: kk                       ! size of 1D vector to be returned
+    REAL(KIND=4), DIMENSION(kk) :: getvare3         ! return e3 variable form the coordinate file
+
+    !! * Local variables   
+    INTEGER, DIMENSION(4) :: istart, icount
+    INTEGER :: ncid, id_var
+    INTEGER :: istatus
+    CHARACTER(LEN=256) :: clvar                      ! local name for cdf var (modified)
+
+    istart(:) = 1
+    icount(:) = 1
+    icount(3)=kk
+    clvar=cdvar
+
+    istatus=NF90_OPEN(cdfile,NF90_NOWRITE,ncid)
+    ! check for IOM style mesh_zgr or coordinates :
+    ! IOIPSL (x_a=y_a=1)               IOM 
+    ! gdept(time,z,y_a,x_a)            gdept_0(t,z)
+    ! 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 ( ncid,'e3t_0',id_var)
+    IF ( istatus == NF90_NOERR) THEN
+     icount(1)=kk ; icount(3)=1
+     SELECT CASE (clvar)
+        CASE ('gdepw') 
+           clvar='gdepw_0'
+        CASE ('gdept')
+           clvar='gdept_0'
+        CASE ('e3t')
+           clvar='e3t_0'
+        CASE ('e3w')
+           clvar='e3w_0'
+      END SELECT
+    ENDIF
+
+    istatus=NF90_INQ_VARID ( ncid,clvar,id_var)
+    istatus=NF90_GET_VAR(ncid,id_var,getvare3,start=istart,count=icount)
+    IF ( istatus /= 0 ) THEN
+       PRINT *,' Problem in getvare3 for ', TRIM(cdvar)
+       PRINT *,TRIM(cdfile), kk
+       CALL ERR_HDL(istatus)
+       STOP
+    ENDIF
+
+    istatus=NF90_CLOSE(ncid)
+  END FUNCTION getvare3
+
+
+  FUNCTION putheadervar(kout, cdfile, kpi,kpj,kpk, pnavlon, pnavlat ,pdep,cdep)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  putheadervar  ***
+    !!
+    !! ** Purpose :  copy header variables from cdfile to the already open ncfile (ncid=kout)
+    !!
+    !! ** Method  :  header variables are nav_lat, nav_lon and either (deptht, depthu, or depthv )
+    !!               Even if the use of different variable name for deptht, depthu depthv is 
+    !!               one of the many non sense of IOIPSL, we are forced to stick with !
+    !!               (Note that these 3 depth are identical in OPA. On the other hand, nav_lon, nav_lat
+    !!                differ for U and V and T points but have the same variable name). 
+    !!               If pnavlon and pnavlat are provided as arguments, they are used for nav_lon, nav_lat
+    !!               instead of the nav_lon,nav_lat read on the file cdfile.
+    !! 
+    !! ** Action  : header variables for file kout is copied from cdfile
+    !!
+    !! history:
+    !!    27/04/2005 : Jean-Marc Molines : Original Code
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+    INTEGER, INTENT(in) :: kout             ! ncid of the outputfile (already open )
+    CHARACTER(LEN=*), INTENT(in) :: cdfile  ! file from where the headers will be copied
+    INTEGER, INTENT(in) :: kpi,kpj,kpk      ! dimension of nav_lon,nav_lat (kpi,kpj), and depht(kpk)
+    REAL(KIND=4), OPTIONAL, DIMENSION(kpi,kpj), INTENT(in) :: pnavlon, pnavlat  ! array provided optionaly to overrid the
+    !                                   !   corresponding arrays in cdfile
+    REAL(KIND=4), OPTIONAL,DIMENSION(kpk), INTENT(in) :: pdep   ! dep array if not on cdfile
+    CHARACTER(LEN=*), OPTIONAL, INTENT(in) :: cdep     ! optional name of vertical variable
+    INTEGER :: putheadervar                 ! return status
+
+    !! * Local variables
+    INTEGER , PARAMETER :: jpdep=6
+    INTEGER :: istatus, idep, jj
+    REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: z2d
+    REAL(KIND=4), DIMENSION(kpk) :: z1d
+    CHARACTER(LEN=256),DIMENSION(jpdep ) :: cldept=(/'deptht ','depthu ','depthv ','depthw ','nav_lev','z      '/)
+    CHARACTER(LEN=256) :: cldep
+
+    ALLOCATE ( z2d (kpi,kpj) )
+    IF (PRESENT(pnavlon) ) THEN 
+       z2d = pnavlon
+    ELSE
+       z2d=getvar(cdfile,'nav_lon', 1,kpi,kpj)
+    ENDIF
+    istatus = putvar(kout,id_lon,z2d,1,kpi,kpj)
+
+    IF (PRESENT(pnavlat) ) THEN
+       z2d = pnavlat
+    ELSE
+       z2d=getvar(cdfile,'nav_lat', 1,kpi,kpj)
+    ENDIF
+
+    istatus = putvar(kout,id_lat,z2d,1,kpi,kpj)
+
+    IF (kpk /= 0 ) THEN
+       IF (PRESENT(pdep) ) THEN
+          z1d = pdep
+       ELSE
+          idep = NF90_NOERR
+
+          IF ( PRESENT (cdep)) THEN
+             z1d=getvar1d(cdfile,cdep,kpk,idep)
+          ENDIF
+
+          IF ( .NOT. PRESENT(cdep) .OR. idep /= NF90_NOERR ) THEN  ! look for standard dep name
+             DO jj = 1,jpdep
+                cldep=cldept(jj)
+                z1d=getvar1d(cdfile,cldep,kpk,idep)
+                IF ( idep == NF90_NOERR )  EXIT
+             END DO
+             IF (jj == jpdep +1 ) THEN
+                PRINT *,' No depth variable found in ', TRIM(cdfile)
+                STOP
+             ENDIF
+          ENDIF
+       ENDIF
+
+       istatus = putvar1d(kout,z1d,kpk,'D')
+    ENDIF
+    putheadervar=istatus
+    DEALLOCATE (z2d)
+
+  END FUNCTION putheadervar
+
+  FUNCTION putvarr8(kout, kid,ptab, klev, kpi, kpj,ktime, kwght)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  putvar  ***
+    !!
+    !! ** Purpose :  copy a 2D level of ptab in already open file kout, using variable kid
+    !!
+    !! ** Method  :
+    !!
+    !! ** Action  : variable level written
+    !!
+    !! history:
+    !!    27/04/2005 : Jean-Marc Molines : Original Code
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+    INTEGER, INTENT(in) :: kout  ,  &       ! ncid of output file
+         &                  kid              ! varid of output variable
+    INTEGER, INTENT(in) :: klev             ! level at which ptab will be written
+    INTEGER, INTENT(in) :: kpi,kpj          ! dimension of ptab
+    INTEGER, OPTIONAL, INTENT(in) :: ktime  ! dimension of ptab
+    INTEGER, OPTIONAL, INTENT(in) :: kwght  ! weight of this variable
+    REAL(KIND=8), DIMENSION(kpi,kpj),INTENT(in) :: ptab ! 2D array to write in file
+    INTEGER :: putvarr8                       ! return status
+
+    !! * Local variables
+    INTEGER :: istatus, itime, id_dimunlim
+    INTEGER, DIMENSION(4) :: istart, icount, nldim
+
+    IF (PRESENT(ktime) ) THEN
+       itime=ktime
+    ELSE
+       itime=1
+    ENDIF
+    istatus=NF90_INQUIRE(kout,unlimitedDimId=id_dimunlim)
+    nldim=0
+    istart(:) = 1
+    istatus=NF90_INQUIRE_VARIABLE(kout, kid,dimids=nldim(:) )
+    IF ( nldim(3) == id_dimunlim)  THEN
+     istart(3)=itime ; istart(4)=1
+    ELSE
+     istart(3)=klev ; istart(4)=itime
+    ENDIF
+    icount(:) = 1 ; icount(1) = kpi ; icount(2) = kpj
+    istatus=NF90_PUT_VAR(kout,kid, ptab, start=istart,count=icount)
+    IF (PRESENT(kwght) ) THEN
+      istatus=NF90_PUT_ATT(kout,kid,'iweight',kwght)
+    ENDIF
+    putvarr8=istatus
+
+  END FUNCTION putvarr8
+
+  FUNCTION putvarr4(kout, kid,ptab, klev, kpi, kpj, ktime, kwght)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  putvar  ***
+    !!
+    !! ** Purpose :  copy a 2D level of ptab in already open file kout, using variable kid
+    !!
+    !! ** Method  :  
+    !!
+    !! ** Action  : variable level written
+    !!
+    !! history:
+    !!    27/04/2005 : Jean-Marc Molines : Original Code
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+    INTEGER, INTENT(in) :: kout  ,  &       ! ncid of output file
+         &                  kid              ! varid of output variable
+    INTEGER, INTENT(in) :: klev             ! level at which ptab will be written
+    INTEGER, INTENT(in) :: kpi,kpj          ! dimension of ptab
+    INTEGER, OPTIONAL, INTENT(in) :: ktime  ! dimension of ptab
+    INTEGER, OPTIONAL, INTENT(in) :: kwght  ! weight of this variable
+    REAL(KIND=4), DIMENSION(kpi,kpj),INTENT(in) :: ptab ! 2D array to write in file
+    INTEGER :: putvarr4                       ! return status
+
+    !! * Local variables    
+    INTEGER :: istatus, itime, id_dimunlim
+    INTEGER, DIMENSION(4) :: istart, icount, nldim
+
+    IF (PRESENT(ktime) ) THEN
+       itime=ktime
+    ELSE
+       itime=1
+    ENDIF
+    istatus=NF90_INQUIRE(kout,unlimitedDimId=id_dimunlim)
+    nldim=0
+    istart(:) = 1 
+    istatus=NF90_INQUIRE_VARIABLE(kout, kid,dimids=nldim(:) )
+    IF ( nldim(3) == id_dimunlim)  THEN
+     istart(3)=itime ; istart(4)=1
+    ELSE
+     istart(3)=klev ; istart(4)=itime
+    ENDIF
+    icount(:) = 1 ; icount(1) = kpi ; icount(2) = kpj
+    istatus=NF90_PUT_VAR(kout,kid, ptab, start=istart,count=icount)
+    IF (PRESENT(kwght) ) THEN
+      istatus=NF90_PUT_ATT(kout,kid,'iweight',kwght)
+    ENDIF
+    putvarr4=istatus
+
+  END FUNCTION putvarr4
+
+  FUNCTION reputvarr4 (cdfile,cdvar,klev,kpi,kpj,kimin,kjmin, ktime,ptab,kwght)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  putvar  ***
+    !!
+    !! ** Purpose :  Change an existing variable in inputfile
+    !!
+    !! ** Method  :  
+    !!
+    !! ** Action  : variable level written
+    !!
+    !! history:
+    !!    27/04/2005 : Jean-Marc Molines : Original Code
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+
+    CHARACTER(LEN=*), INTENT(in) :: cdfile,     &   ! file name to work with
+         &                          cdvar           ! variable name to work with
+    INTEGER, INTENT(in) :: kpi,kpj                  ! horizontal size of the 2D variable
+    INTEGER, OPTIONAL, INTENT(in) :: klev           ! Optional variable. If missing 1 is assumed
+    INTEGER, OPTIONAL, INTENT(in) :: kimin,kjmin    ! Optional variable. If missing 1 is assumed
+    INTEGER, OPTIONAL, INTENT(in) :: ktime          ! Optional variable. If missing 1 is assumed
+    INTEGER, OPTIONAL, INTENT(in) :: kwght          ! weight of this variable
+    REAL(KIND=4), DIMENSION(kpi,kpj) ::  ptab     ! 2D REAL 4 holding variable field at klev
+    INTEGER :: reputvarr4
+
+    !! * Local variables
+    INTEGER, DIMENSION(4) :: istart, icount, nldim
+    INTEGER :: ncid, id_var, id_dimunlim
+    INTEGER :: istatus, ilev, imin, jmin, itime
+
+    ilev=1  ; IF (PRESENT(klev)  ) ilev=klev
+    imin=1  ; IF (PRESENT(kimin) ) imin=kimin
+    jmin=1  ; IF (PRESENT(kjmin) ) jmin=kjmin
+    itime=1 ; IF (PRESENT(ktime) ) itime=ktime
+
+    istatus=NF90_OPEN(cdfile,NF90_WRITE,ncid)
+    istatus=NF90_INQ_VARID(ncid,cdvar,id_var)
+    !! look for eventual unlimited dim (time_counter)
+    istatus=NF90_INQUIRE(ncid,unlimitedDimId=id_dimunlim)
+    
+    nldim=0
+    istatus=NF90_INQUIRE_VARIABLE(ncid, id_var,dimids=nldim(:) )
+    ! if the third dim of id_var is time, then adjust the starting point to take ktime into account (case XYT file)
+    IF ( nldim(3) == id_dimunlim)  THEN ; ilev=itime ; itime=1 ; ENDIF
+    istatus=NF90_PUT_VAR(ncid,id_var,ptab,start=(/imin,jmin,ilev,itime/), count=(/kpi,kpj,1,1/) )
+    !PRINT *,TRIM(NF90_STRERROR(istatus)),' in reputvar'
+    IF (PRESENT(kwght)) THEN
+      istatus=NF90_PUT_ATT(ncid,id_var,'iweight',kwght)
+    ENDIF
+    reputvarr4=istatus
+    istatus=NF90_CLOSE(ncid)
+
+  END FUNCTION reputvarr4
+
+  FUNCTION putvarzo(kout, kid,ptab, klev, kpi, kpj,ktime)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  putvarzo  ***
+    !!
+    !! ** Purpose :  copy a 2D level of ptab in already open file kout, using variable kid
+    !!               This variant deals with degenerated 2D (1 x jpj) zonal files
+    !!
+    !! ** Method  :
+    !!
+    !! ** Action  : variable level written
+    !!
+    !! history:
+    !!    27/04/2005 : Jean-Marc Molines : Original Code
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+    INTEGER, INTENT(in) :: kout  ,  &       ! ncid of output file
+         &                  kid              ! varid of output variable
+    INTEGER, INTENT(in) :: klev             ! level at which ptab will be written
+    INTEGER, INTENT(in) :: kpi,kpj          ! dimension of ptab
+    INTEGER, OPTIONAL, INTENT(in) :: ktime  ! dimension of ptab
+    REAL(KIND=4), DIMENSION(kpj),INTENT(in) :: ptab ! 2D array to write in file
+    INTEGER :: putvarzo                       ! return status
+
+    !! * Local variables
+    INTEGER :: istatus, itime, ilev, id_dimunlim
+    INTEGER, DIMENSION(4) :: istart, icount,nldim
+
+    ilev=klev
+    IF (PRESENT(ktime) ) THEN
+       itime=ktime
+    ELSE
+       itime=1
+    ENDIF
+
+     ! look for unlimited dim (time_counter)
+    istatus=NF90_INQUIRE(kout,unlimitedDimId=id_dimunlim)
+    nldim=0
+    istatus=NF90_INQUIRE_VARIABLE(kout,kid,dimids=nldim(:) )
+    !  if the third dim of id_var is time, then adjust the starting point to take ktime into account (case XYT file)
+    IF ( nldim(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
+    istatus=NF90_PUT_VAR(kout,kid, ptab, start=istart,count=icount)
+    putvarzo=istatus
+
+  END FUNCTION putvarzo
+
+
+  FUNCTION putvari2(kout, kid,ptab, klev, kpi, kpj,ktime)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  putvar  ***
+    !!
+    !! ** Purpose :  copy a 2D level of ptab in already open file kout, using variable kid
+    !!
+    !! ** Method  :
+    !!
+    !! ** Action  : variable level written
+    !!
+    !! history:
+    !!    27/04/2005 : Jean-Marc Molines : Original Code
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+    INTEGER, INTENT(in) :: kout  ,  &       ! ncid of output file
+         &                  kid              ! varid of output variable
+    INTEGER, INTENT(in) :: klev             ! level at which ptab will be written
+    INTEGER, INTENT(in) :: kpi,kpj          ! dimension of ptab
+    INTEGER, OPTIONAL, INTENT(in) :: ktime  ! dimension of ptab
+    INTEGER(KIND=2), DIMENSION(kpi,kpj),INTENT(in) :: ptab ! 2D array to write in file
+    INTEGER :: putvari2                       ! return status
+
+    !! * Local variables
+    INTEGER :: istatus, itime, ilev, id_dimunlim
+    INTEGER, DIMENSION(4) :: istart, icount, nldim
+
+    ilev=klev
+    IF (PRESENT(ktime) ) THEN
+       itime=ktime
+    ELSE
+       itime=1
+    ENDIF
+    ! idem above for XYT files
+    istatus=NF90_INQUIRE(kout,unlimitedDimId=id_dimunlim)
+    nldim=0
+    istart(:) = 1
+    istatus=NF90_INQUIRE_VARIABLE(kout, kid,dimids=nldim(:) )
+    IF ( nldim(3) == id_dimunlim)  THEN
+     istart(3)=itime ; istart(4)=1
+    ELSE
+     istart(3)=ilev ; istart(4)=itime
+    ENDIF
+
+    icount(:) = 1 ; icount(1) = kpi ; icount(2) = kpj
+    istatus=NF90_PUT_VAR(kout,kid, ptab, start=istart,count=icount)
+    putvari2=istatus
+
+  END FUNCTION putvari2
+
+
+  FUNCTION putvar1d(kout,ptab,kk,cdtype)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  putvar1d  ***
+    !!
+    !! ** Purpose : Copy 1D variable (size kk) hold in ptab,  with id kid, into file id kout
+    !!
+    !! ** Method  :  cdtype is either T (time_counter) or D (depth?)
+    !!
+    !! ** Action  : 1D variable  written
+    !!
+    !! history:
+    !!    27/04/2005 : Jean-Marc Molines : Original Code
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+    INTEGER, INTENT(in) :: kout             ! ncid of output file
+    INTEGER, INTENT(in) :: kk               ! number of elements in ptab
+    REAL(KIND=4), DIMENSION(kk),INTENT(in) :: ptab ! 1D array to write in file
+    CHARACTER(LEN=1), INTENT(in)  :: cdtype ! either T or D
+    INTEGER :: putvar1d                     ! return status
+
+    !! * Local variables     
+    INTEGER :: istatus, iid
+    INTEGER, DIMENSION(1) :: istart, icount
+
+    SELECT CASE ( cdtype )
+    CASE ('T', 't' ) 
+       iid = id_tim
+    CASE ('D', 'd' )
+       iid = id_dep
+    END SELECT
+
+    istart(:) = 1
+    icount(:) = kk
+    istatus=NF90_PUT_VAR(kout,iid, ptab, start=istart,count=icount)
+    putvar1d=istatus
+
+  END FUNCTION putvar1d
+
+  FUNCTION putvar0d(kout,varid,value)
+    !!-----------------------------------------------------------
+    !!                       ***  FUNCTION  putvar0d  ***
+    !!
+    !! ** Purpose : Copy single value, with id varid, into file id kout
+    !!
+    !! ** Method  :  
+    !!
+    !! ** Action  : single value variable  written
+    !!
+    !!-----------------------------------------------------------
+    !! * Arguments declarations
+    INTEGER, INTENT(in) :: kout             ! ncid of output file
+    INTEGER, INTENT(in) :: varid            ! id of the variable
+    REAL(KIND=4), INTENT(in) :: value ! single value to write in file
+    INTEGER :: putvar0d                     ! return status
+
+    ! Local variables
+    INTEGER :: istatus
+
+    istatus=NF90_PUT_VAR(kout,varid,value)
+    putvar0d=istatus
+
+  END FUNCTION putvar0d
+
+  FUNCTION closeout(kout)
+    !!----------------------------------------------------------
+    !!                       ***  FUNCTION  closeout  ***
+    !!
+    !! ** Purpose : close open output files
+    !!
+    !! history:
+    !!    27/04/2005 : Jean-Marc Molines : Original Code
+    !!-----------------------------------------------------------
+    INTEGER,INTENT(in) :: kout   ! ncid of file to be closed
+    INTEGER :: closeout          ! return status
+    closeout=NF90_CLOSE(kout)
+  END FUNCTION closeout
+
+  FUNCTION ncopen(cdfile)
+    !!----------------------------------------------------------
+    !!                       ***  FUNCTION  ncopen  ***
+    !!
+    !! ** Purpose : open file cdfile and return file ID
+    !!
+    !!-----------------------------------------------------------
+      CHARACTER(LEN=*), INTENT(in) :: cdfile ! file name
+      INTEGER :: ncopen                      ! return status
+    ! * Local variables
+      INTEGER :: istatus, ncid
+      istatus = NF90_OPEN(cdfile,NF90_WRITE,ncid)
+      ncopen=ncid
+  END FUNCTION ncopen
+
+  SUBROUTINE ERR_HDL(kstatus)
+    !! ----------------------------------------------------------
+    !!   ***  SUBROUTINE err_hdl
+    !!
+    !!   ** Purpose :  Error handle for NetCDF routine.
+    !!          Stop if kstatus indicates error conditions.
+    !!
+    !! History :
+    !!     Original: J.M. Molines (01/99)
+    !!
+    !! -----------------------------------------------------------
+    IMPLICIT NONE
+    INTEGER, INTENT(in) ::  kstatus
+    IF (kstatus /=  NF90_NOERR ) THEN
+       PRINT *, 'ERROR in NETCDF routine, status=',kstatus
+       PRINT *,NF90_STRERROR(kstatus)
+       STOP
+    END IF
+  END SUBROUTINE ERR_HDL
+
+  SUBROUTINE gettimeseries (cdfile, cdvar, kilook, kjlook,klev)
+    !! ----------------------------------------------------------
+    !!   ***  SUBROUTINE gettimeseries  ***
+    !!
+    !!   ** Purpose : Display a 2 column output ( time, variable) for
+    !!           a given variable of a given file at a given point
+    !!
+    !! History :
+    !!     Original: J.M. Molines (03/2007)
+    !!
+    !! -----------------------------------------------------------
+    !* Arguments
+    IMPLICIT NONE
+    CHARACTER(LEN=*),INTENT(in) :: cdfile, cdvar
+    INTEGER,INTENT(in) :: kilook,kjlook
+    INTEGER, OPTIONAL, INTENT(in) :: klev
+    !* Local variables
+    INTEGER ::  nt, jt
+    REAL(KIND=4), DIMENSION(:), ALLOCATABLE :: ztime, zval
+    REAL(KIND=4) :: ztmp, zao=0., zsf=1.0   !: add_offset, scale_factor
+
+    ! netcdf stuff
+    INTEGER :: istatus
+    INTEGER :: ncid, id_t, id_var, ndim, jk
+
+    ! Klev can be used to give the model level we want to look at
+    IF ( PRESENT(klev) ) THEN
+       jk=klev
+    ELSE
+       jk=1
+    ENDIF
+
+    ! Open cdf dataset
+    istatus=NF90_OPEN(cdfile,NF90_NOWRITE,ncid)
+
+    ! read time dimension
+    istatus=NF90_INQ_DIMID(ncid,'time_counter',id_t)
+    istatus=NF90_INQUIRE_DIMENSION(ncid,id_t,len=nt)
+
+    ! Allocate space
+    ALLOCATE (ztime(nt), zval(nt) )
+
+    ! gettime
+    istatus=NF90_INQ_VARID(ncid,'time_counter',id_var)
+    istatus=NF90_GET_VAR(ncid,id_var,ztime,(/1/),(/nt/) )
+
+    ! read variable
+    istatus=NF90_INQ_VARID(ncid,cdvar,id_var)
+    !   look for scale_factor and add_offset attribute:
+    istatus=NF90_GET_ATT(ncid,id_var,'add_offset',ztmp)
+    IF ( istatus == NF90_NOERR ) zao = ztmp
+    istatus=NF90_GET_ATT(ncid,id_var,'scale_factor',ztmp)
+    IF ( istatus == NF90_NOERR ) zsf = ztmp
+
+    ! get number of dimension of the variable ( either x,y,t or x,y,z,t )
+    istatus=NF90_INQUIRE_VARIABLE(ncid,id_var,ndims=ndim)
+    IF ( ndim == 3 ) THEN
+       istatus=NF90_GET_VAR(ncid,id_var,zval,(/kilook,kjlook,1/),(/1,1,nt/) )
+    ELSE IF ( ndim == 4 ) THEN
+       istatus=NF90_GET_VAR(ncid,id_var,zval,(/kilook,kjlook,jk,1/),(/1,1,1,nt/) )
+    ELSE 
+       PRINT *,'  ERROR : variable ',TRIM(cdvar),' has ', ndim, &
+            &       ' dimensions !. Only 3 or 4 supported'
+       STOP
+    ENDIF
+
+    ! convert to physical values
+    zval=zval*zsf + zao
+
+    ! display results :
+    DO jt=1,nt
+       PRINT *,ztime(jt)/86400., zval(jt)
+    ENDDO
+
+    istatus=NF90_CLOSE(ncid)
+
+  END SUBROUTINE gettimeseries
+
+END MODULE cdfio
+

+ 241 - 0
cdftools_light/src/cdfmaxmoc.f90

@@ -0,0 +1,241 @@
+PROGRAM cdfmaxmoc
+   !!---------------------------------------------------------------------------------------------------
+   !!              ***  PROGRAM cdfmaxmoc  ***
+   !!
+   !!   ** Purpose : Compute the maximum of the overturning fonction from a file calculated by cdfmoc
+   !!
+   !!   ** Method : maxovt 'ovtfile' latmin latmax depmin depmax
+   !!               return ovtmaximum and ovt minimum in the defined range.
+   !!               Also give location of those extrema
+   !!               works for Atlantic and Global MOC
+   !!
+   !!  * history:
+   !!              July 2005 : original : J.M. Molines
+   !!              November :  modified and adapted to cdf output R. Dussin.
+   !!---------------------------------------------------------------------------------------------------
+   !!  $Rev: 319 $
+   !!  $Date: 2010-05-19 12:19:07 +0200 (Wed, 19 May 2010) $
+   !!  $Id: cdfmaxmoc.f90 319 2010-05-19 10:19:07Z dussin $
+   !!--------------------------------------------------------------
+
+   USE netcdf
+
+   USE cdfio
+   USE io_ezcdf
+
+   IMPLICIT NONE
+   !!
+   INTEGER :: jj, jk, jt,    jt_pos             ! dummy loop index  !LB
+   INTEGER :: id_moc, id_lat_max, id_depthw_max, idd_t, idv_time, idf_out
+   LOGICAL :: lfncout
+   INTEGER :: npjglo, npk, nt           ! size of the overturning !LB
+   INTEGER :: narg, iargc, istatus       ! line command stuff
+   INTEGER :: jmin, jmax, kmin, kmax    ! (latitude, depth) window where to look at extrema
+   INTEGER :: imaxloc(3)    ! temporary array to use with minloc/maxloc
+   ! added to write in netcdf
+   INTEGER :: kx=1, ky=1, kz=1          ! dims of netcdf output file
+   INTEGER :: nboutput=6                ! number of values to write in cdf output
+   INTEGER :: ncout, ierr               ! for netcdf output
+   INTEGER, DIMENSION(:), ALLOCATABLE ::  ipk, id_varout
+   !
+   REAL(KIND=4), DIMENSION(:,:,:), ALLOCATABLE ::  zomoc   ! zonal MOC (1,npjglo,jpk)
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE ::    rlat    ! latitude (1, npjglo)
+   REAL(KIND=4), DIMENSION(:), ALLOCATABLE   ::   gdepw    ! depth read in the header
+
+   REAL(KIND=4), DIMENSION(:), ALLOCATABLE ::   ovtmax
+   INTEGER,      DIMENSION(:), ALLOCATABLE ::   jlatmax, kdmax
+
+
+   CHARACTER(len=4)                          ::   clatmin, clatmax
+   REAL(KIND=4)                              ::   rlatmin, rlatmax, depmin , depmax
+   ! added to write in netcdf
+   REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE ::  dumlon, dumlat
+   REAL(KIND=4), DIMENSION (1)               ::  tim ! time counter
+   TYPE(variable), DIMENSION(:), ALLOCATABLE :: typvar  ! structure of output
+   !
+   CHARACTER(LEN=256) :: cdum, cfile, comment, cbasin, cvar, cdep, ctim, cv_dum
+   CHARACTER(LEN=512) :: cd_out='.', cf_out
+
+
+   REAL(4) :: ryear, rmon, rdt
+
+   INTEGER :: idf_moc=0 , idv_moc=0
+
+
+   ! * main program
+   narg=iargc()
+   IF (narg == 8) THEN
+      CALL getarg(1,cfile)
+      CALL getarg(2,cbasin)
+      CALL getarg(3,cdum)
+      READ(cdum,*) rlatmin
+      CALL getarg(4,cdum)
+      READ(cdum,*) rlatmax
+      CALL getarg(5,cdum)
+      READ(cdum,*) depmin
+      CALL getarg(6,cdum)
+      READ(cdum,*) depmax
+      CALL getarg(7,cdum)
+      READ(cdum,*) ryear
+      CALL getarg(8,cd_out)
+   ELSE
+      PRINT *,' USAGE: cdfmaxmoc ''ovt_file.nc'' cbasin latmin latmax depmin depmax <year> <DIROUT>'
+      PRINT *,'        cbasin is one of atl glo inp ind or pac '
+      PRINT *,' Output on standard output by default and maxmoc.nc '
+      STOP
+   ENDIF
+
+
+
+   npjglo = getdim(cfile,'y')
+   cdep='none'
+   npk    = getdim(cfile,'depth',cdtrue=cdep,kstatus=istatus) !LB
+   ctim='none'
+   nt     = getdim(cfile,'time', cdtrue=ctim,kstatus=istatus) !LB
+
+
+   ALLOCATE ( zomoc (1,npjglo,npk) ,gdepw(npk), rlat(1,npjglo), ovtmax(nt), jlatmax(nt), kdmax(nt) )
+   gdepw(:)  = -getvar1d(cfile,'depthw',npk)
+   rlat(:,:) = getvar(cfile,'nav_lat',1,1,npjglo)
+
+   SELECT CASE (cbasin)
+   CASE ('atl')
+      cvar='zomsfatl'
+   CASE ('glo')
+      cvar='zomsfglo'
+   CASE ('pac')
+      cvar='zomsfpac'
+   CASE ('inp')
+      cvar='zomsfinp'
+   CASE ('ind')
+      cvar='zomsfind'
+   CASE DEFAULT
+      STOP 'basin not found'
+   END SELECT
+
+
+   ! look for jmin-jmax :
+   DO jj=1, npjglo
+      IF ( rlat(1,jj) <= rlatmin )  jmin = jj
+      IF ( rlat(1,jj) <= rlatmax )  jmax = jj
+   END DO
+
+   ! look for kmin kmax
+   DO jk=1,npk
+      IF ( gdepw(jk) <= depmin ) kmin = jk
+      IF ( gdepw(jk) <= depmax ) kmax = jk
+   END DO
+
+
+   DO jt = 1, nt !LB
+
+      !PRINT *, ' * [cdfmaxmoc] jt = ', jt
+      CALL GETVAR_3D(idf_moc, idv_moc,  cfile, cvar, nt, jt, zomoc)
+
+      ! look for max/min overturning
+      ovtmax(jt) = MAXVAL(zomoc(1,jmin:jmax,kmin:kmax))
+
+      ! find location of min/max
+      !iminloc =MINLOC(zomoc(:,jmin:jmax,kmin:kmax))
+      imaxloc =MAXLOC(zomoc(:,jmin:jmax,kmin:kmax))
+
+      ! results from minloc/maxloc is relative to the sub -array given as arguments
+      jlatmax(jt) = imaxloc(2)+jmin -1
+      kdmax(jt)   = imaxloc(3)+kmin -1
+
+   END DO !LB nt
+
+
+
+   WRITE( clatmin, '(i2.2)') INT(ABS(rlatmin))
+   WRITE( clatmax, '(i2.2)') INT(ABS(rlatmax))
+
+   IF ( rlatmin >= 0. ) THEN
+      clatmin = '+'//trim(clatmin)//'N'
+   ELSE
+      clatmin = '-'//trim(clatmin)//'N'
+   END IF
+   IF ( rlatmax >= 0. ) THEN
+      clatmax = '+'//trim(clatmax)//'N'
+   ELSE
+      clatmax = '-'//trim(clatmax)//'N'
+   END IF
+
+
+
+   WRITE( cf_out , '(a,"/max_moc_",a,"_",2a,".nc")' ) trim(cd_out), trim(cbasin), clatmin, clatmax
+   
+   id_moc = 0 ; id_lat_max = 0 ; id_depthw_max = 0
+
+   INQUIRE( FILE=cf_out, EXIST=lfncout )
+   
+   IF ( .NOT. lfncout ) THEN
+
+      !! Creating file
+      PRINT *, ' Creating file '//trim(cf_out)//' !!!'
+      ierr = NF90_CREATE(cf_out, NF90_CLOBBER, idf_out)
+      ierr = NF90_DEF_DIM(idf_out, 'time', NF90_UNLIMITED, idd_t)
+      ierr = NF90_DEF_VAR(idf_out, 'time', NF90_DOUBLE,    idd_t, idv_time)
+
+
+      ierr = NF90_DEF_VAR(idf_out, 'moc_'//trim(cbasin), NF90_FLOAT, (/idd_t/), id_moc)
+      ierr = NF90_PUT_ATT(idf_out, id_moc, 'long_name', 'Meridional Overturning Circulation')
+      ierr = NF90_PUT_ATT(idf_out, id_moc, 'units', 'Sv')
+
+      ierr = NF90_DEF_VAR(idf_out, 'lat_max_'//trim(cbasin), NF90_FLOAT, (/idd_t/), id_lat_max)
+      ierr = NF90_PUT_ATT(idf_out, id_lat_max, 'long_name', 'Latitude for maximum of MOC')
+      ierr = NF90_PUT_ATT(idf_out, id_lat_max, 'units', 'deg.N')
+
+      ierr = NF90_DEF_VAR(idf_out, 'depthw_max_'//trim(cbasin), NF90_FLOAT, (/idd_t/), id_depthw_max)
+      ierr = NF90_PUT_ATT(idf_out, id_depthw_max, 'long_name', 'W-depth for maximum of MOC')
+      ierr = NF90_PUT_ATT(idf_out, id_depthw_max, 'units', 'm')
+
+
+      ierr = NF90_PUT_ATT(idf_out, NF90_GLOBAL, 'About', &
+         &   'Created by BaraKuda (cdfmaxmoc.f90) => https://github.com/brodeau/barakuda')
+
+      ierr = NF90_ENDDEF(idf_out)
+      jt_pos = 0
+
+   ELSE
+
+      !! Opening already existing file
+      ierr = NF90_OPEN  (cf_out, NF90_WRITE,   idf_out)
+
+      !! Need IDs of variables to append... NF90_INQ_VARID
+      ierr = NF90_INQ_VARID(idf_out, 'moc_'//trim(cbasin), id_moc)
+
+      !! Need IDs of variables to append... NF90_INQ_VARID
+      ierr = NF90_INQ_VARID(idf_out, 'lat_max_'//trim(cbasin), id_lat_max)
+
+      !! Need IDs of variables to append... NF90_INQ_VARID
+      ierr = NF90_INQ_VARID(idf_out, 'depthw_max_'//trim(cbasin), id_depthw_max)
+
+      ! Get ID of unlimited dimension
+      ierr = NF90_INQUIRE(idf_out, unlimitedDimId = idv_time)
+
+      ! Need to know jt_pos, record number of the last time record writen in the file
+      ierr = NF90_INQUIRE_DIMENSION(idf_out, idv_time, name=cv_dum, len=jt_pos)
+
+   END IF
+
+   WRITE(*,'("Going to write record ",i4.4," to ",i4.4," into ",a)') jt_pos+1, jt_pos+1+nt, trim(cf_out)
+
+   DO jt = 1, nt
+
+      ! Writing record jt for time vector and 1d fields:
+      ierr = NF90_PUT_VAR( idf_out, idv_time, (/ryear+1./12.*(REAL(jt)-1.+0.5)/), start=(/jt_pos+jt/), count=(/1/) )
+
+      !! Default variable is the only one present (index = 1) :
+      ierr = NF90_PUT_VAR(idf_out, id_moc, (/ ovtmax(jt) /), start=(/jt_pos+jt/), count=(/1/))
+      ierr = NF90_PUT_VAR(idf_out, id_lat_max, (/ rlat(1,jlatmax(jt)) /), start=(/jt_pos+jt/), count=(/1/))
+      ierr = NF90_PUT_VAR(idf_out, id_depthw_max, (/ gdepw(kdmax(jt)) /), start=(/jt_pos+jt/), count=(/1/))
+      
+   END DO
+
+   ierr = NF90_CLOSE(idf_out)
+
+   PRINT *, ''
+
+
+END PROGRAM cdfmaxmoc

+ 362 - 0
cdftools_light/src/cdfmean.f90

@@ -0,0 +1,362 @@
+PROGRAM cdfmean
+  !!-------------------------------------------------------------------
+  !!               ***  PROGRAM cdfmean  ***
+  !!
+  !!  **  Purpose  :  Compute the Mean Value over the ocean
+  !!                  PARTIAL STEPS
+  !!  
+  !!  **  Method   :  compute the sum ( V * e1 *e2 * e3 *mask )/ sum( e1 * e2 * e3 *mask )
+  !!
+  !!
+  !! history ;
+  !!  Original :  J.M. Molines (Oct. 2005) 
+  !!              R. Dussin (Jul 2009) : add cdf output
+  !!-------------------------------------------------------------------
+  !!  $Rev: 319 $
+  !!  $Date: 2010-05-19 12:19:07 +0200 (Wed, 19 May 2010) $
+  !!  $Id: cdfmean.f90 319 2010-05-19 10:19:07Z dussin $
+  !!--------------------------------------------------------------
+  !! * Modules used
+  USE cdfio
+
+  !! * Local variables
+  IMPLICIT NONE
+  INTEGER   :: jk, ik, jt, jj
+  INTEGER   :: imin=0, imax=0, jmin=0, jmax=0      !: domain limitation for computation
+  INTEGER   :: kmin=0, kmax=0                      !: domain limitation for computation
+  INTEGER   :: narg, iargc                         !: command line 
+  INTEGER   :: npiglo,npjglo, npk, nt              !: size of the domain
+  INTEGER   :: nvpk                                !: vertical levels in working variable
+  INTEGER   :: numout=10                           !: logical unit for output file
+  ! added to write in netcdf
+  INTEGER :: kx=1, ky=1                ! dims of netcdf output file
+  INTEGER :: nvars=2                ! number of values to write in cdf output
+  INTEGER :: ncout, ierr               ! for netcdf output
+  INTEGER, DIMENSION(:), ALLOCATABLE ::  ipk, id_varout
+  !
+  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 
+  ! added to write in netcdf
+  REAL(KIND=4) :: threedmeanout, pmissing_value
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE ::  dumlon, dumlat, dummymean
+  REAL(KIND=4), DIMENSION (1)               ::  tim ! time counter
+  REAL(KIND=4), DIMENSION(:), ALLOCATABLE :: meanout
+  REAL(KIND=8), DIMENSION(:), ALLOCATABLE :: year_mean
+  TYPE(variable), DIMENSION(:), ALLOCATABLE :: typvar  ! structure of output
+  !
+  REAL(KIND=8)      :: zvol, zsum, zvol2d, zsum2d, zsurf
+  CHARACTER(LEN=256) :: cfilev , cdum, cf_out, cf_asout
+  CHARACTER(LEN=256) :: coordhgr='mesh_hgr.nc',  coordzgr='mesh_zgr.nc',cmask='mask.nc'
+  CHARACTER(LEN=256) :: cvar, cvartype, cdep, ctim
+  CHARACTER(LEN=20) :: ce1, ce2, ce3, cvmask, cvtype
+  CHARACTER(LEN=256) :: cfilout='out.txt'
+  ! added to write in netcdf
+  CHARACTER(LEN=256) :: cfileoutnc
+  CHARACTER(LEN=256) :: cdunits, cdlong_name, cdshort_name 
+  ! added to write in netcdf
+  LOGICAL :: lwrtcdf=.TRUE., l_pvp
+  !LOGICAL :: lwrtcdf=.TRUE., l_treat_ssh, l_pvp
+
+
+  INTEGER    :: istatus
+
+  ! constants
+
+  !!  Read command line and output usage message if not compliant.
+  narg= iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' Usage : cdfmean  ncfile cdfvar T| U | V | F | W  file_ascii_out  [imin imax jmin jmax kmin kmax] '
+     PRINT *,' Computes the mean value of the field (3D, weighted) '
+     PRINT *,' imin imax jmin jmax kmin kmax can be given in option '
+     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 *,' PARTIAL CELLS VERSION'
+     PRINT *,' Files mesh_hgr.nc, mesh_zgr.nc ,mask.nc '
+     PRINT *,'  must be in the current directory'
+     PRINT *,' Output on standard output'
+     STOP
+  ENDIF
+  ! Open standard output with recl=256 to avoid wrapping of long lines (ifort)
+  !LB:
+  !OPEN(6,FORM='FORMATTED',RECL=256)
+  !LB.
+  
+  CALL getarg (1, cfilev)
+  CALL getarg (2, cvar)
+  CALL getarg (3, cvartype)
+  CALL getarg (4, cf_asout) !LB
+
+  IF (narg > 4 ) THEN
+     IF ( narg /= 10 ) THEN
+        PRINT *, ' ERROR : You must give 6 optional values (imin imax jmin jmax kmin kmax)'
+        STOP
+     ELSE
+        ! input optional imin imax jmin jmax
+        CALL getarg ( 5,cdum) ; READ(cdum,*) imin
+        CALL getarg ( 6,cdum) ; READ(cdum,*) imax
+        CALL getarg ( 7,cdum) ; READ(cdum,*) jmin
+        CALL getarg ( 8,cdum) ; READ(cdum,*) jmax
+        CALL getarg ( 9,cdum) ; READ(cdum,*) kmin
+        CALL getarg ( 10,cdum) ; READ(cdum,*) kmax
+     ENDIF
+  ENDIF
+
+  cdep='none'
+  npiglo= getdim (cfilev,'x')
+  npjglo= getdim (cfilev,'y')
+  npk   = getdim (cfilev,'depth',cdtrue=cdep,kstatus=istatus)
+  
+
+  !LB: fix bug SSH with ORCA025.L75
+  !l_treat_ssh = .FALSE.
+  !IF ( (trim(cvar) == 'sossheig').AND.(npiglo == 1442).AND.(npjglo == 1021) ) THEN
+  !   PRINT *, '' ; PRINT *, 'BUG !!! This is sossheig on ORCA025 !!!'; PRINT *, ''
+  !   l_treat_ssh = .TRUE.
+  !END IF
+
+
+
+  
+  !LB:
+  l_pvp = .FALSE.
+  IF ( (kmin == 0).AND.(kmax == 0) ) l_pvp = .TRUE.
+  !PRINT *, 'npk, kmin, kmax, l_pvp =', npk, kmin, kmax, l_pvp; PRINT *, ''
+  !LB.
+  
+
+  IF (istatus /= 0 ) THEN
+     npk   = getdim (cfilev,'z',cdtrue=cdep,kstatus=istatus)
+     IF (istatus /= 0 ) THEN
+       npk   = getdim (cfilev,'sigma',cdtrue=cdep,kstatus=istatus)
+        IF ( istatus /= 0 ) THEN
+          npk = getdim (cfilev,'nav_lev',cdtrue=cdep,kstatus=istatus)
+            IF ( istatus /= 0 ) THEN
+              PRINT *,' assume file with no depth'
+              npk=0
+            ENDIF
+        ENDIF
+     ENDIF
+  ENDIF
+  
+  ctim = 'none'
+  nt    = getdim (cfilev,'time',cdtrue=ctim,kstatus=istatus) !LB
+
+  nvpk  = getvdim(cfilev,cvar)
+
+  IF (npk == 0  ) THEN ; npk = 1              ; ENDIF  ! no depth dimension ==> 1 level
+  IF (imin /= 0 ) THEN ; npiglo=imax -imin + 1;  ELSE ; imin=1 ; ENDIF
+  IF (jmin /= 0 ) THEN ; npjglo=jmax -jmin + 1;  ELSE ; jmin=1 ; ENDIF
+  IF (kmin /= 0 ) THEN ; npk   =kmax -kmin + 1;  ELSE ; kmin=1 ; ENDIF
+
+  IF (nvpk == 2 ) nvpk = 1
+  IF (nvpk == 3 ) nvpk = npk
+  
+
+
+
+  !LB:
+  OPEN(16, FILE = cf_asout, FORM='FORMATTED', RECL=256)
+
+
+  WRITE(16, *) 'npiglo=', npiglo
+  WRITE(16, *) 'npjglo=', npjglo
+  WRITE (16,*) 'npk   =', npk
+  WRITE (16,*) 'nt    =', nt
+  WRITE (16,*) 'nvpk  =', nvpk
+  WRITE (16,*) 'depth dim name is ', TRIM(cdep)
+
+
+
+  ! Allocate arrays
+  ALLOCATE ( zmask(npiglo,npjglo) )
+  ALLOCATE ( zv(npiglo,npjglo) )
+  ALLOCATE ( e1(npiglo,npjglo),e2(npiglo,npjglo), e3(npiglo,npjglo) )
+  ALLOCATE ( gdep (npk) )
+  SELECT CASE (TRIM(cvartype))
+     CASE ( 'T' )
+        ce1='e1t'
+        ce2='e2t'
+        ce3='e3t_0'
+        cvmask='tmask'
+        cdep='gdept'
+     CASE ( 'U' )
+        ce1='e1u'
+        ce2='e2u'
+        ce3='e3t_0'
+        cvmask='umask'
+        cdep='gdept'
+     CASE ( 'V' )
+        ce1='e1v'
+        ce2='e2v'
+        ce3='e3t_0'
+        cvmask='vmask'
+        cdep='gdept'
+     CASE ( 'F' )
+        ce1='e1f'
+        ce2='e2f'
+        ce3='e3t_0'
+        cvmask='fmask'
+        cdep='gdept'
+     CASE ( 'W' )
+        ce1='e1t'
+        ce2='e2t'
+        ce3='e3w_0'
+        cvmask='tmask'
+        cdep='gdepw'
+     CASE DEFAULT
+        PRINT *, 'this type of variable is not known :', TRIM(cvartype)
+        STOP
+  END SELECT
+
+
+  e1(:,:) = getvar(coordhgr, ce1, 1,npiglo,npjglo,kimin=imin,kjmin=jmin)
+  e2(:,:) = getvar(coordhgr, ce2, 1,npiglo,npjglo,kimin=imin,kjmin=jmin)
+  gdep(:) = getvare3(coordzgr,cdep,npk)
+
+
+  IF(lwrtcdf) THEN
+      ALLOCATE ( typvar(nvars), ipk(nvars), id_varout(nvars) )
+      ALLOCATE (dumlon(kx,ky) , dumlat(kx,ky), dummymean(kx,ky) )
+      ALLOCATE ( meanout(npk) , year_mean(npk) )
+
+      dumlon(:,:)=0.
+      dumlat(:,:)=0.
+
+      ipk(1)=npk ! mean for each level
+      ipk(2)=1   ! 3D mean
+
+
+      ierr=getvaratt (cfilev,cvar,cdunits, &
+                pmissing_value, cdlong_name, cdshort_name)
+
+      ! define new variables for output 
+      typvar(1)%name='mean_'//TRIM(cvar)
+      typvar%units=TRIM(cdunits)
+      typvar%missing_value=99999.
+      typvar%valid_min= -1000.
+      typvar%valid_max= 1000.
+      typvar%scale_factor= 1.
+      typvar%add_offset= 0.
+      typvar%savelog10= 0.
+      typvar(1)%long_name='mean_'//TRIM(cdlong_name)
+      typvar(1)%short_name='mean_'//TRIM(cdshort_name)
+      typvar%online_operation='N/A'
+      typvar%axis='ZT'
+
+      typvar(2)%name='mean_3D'//TRIM(cvar)
+      typvar(2)%long_name='mean_3D'//TRIM(cdlong_name)
+      typvar(2)%short_name='mean_3D'//TRIM(cdshort_name)
+      typvar%online_operation='N/A'
+      typvar%axis='T'
+   ENDIF
+
+
+
+
+   !LB:
+   OPEN(numout,FILE=cfilout)
+   WRITE(numout,*) '# Time, '//trim(cvar)//',   Depth,    level'
+   !LB.
+
+
+   IF ( nt < 1 ) THEN
+      PRINT *, 'ERROR: the file contains no time records! nt =', nt
+      STOP
+   END IF
+
+
+   DO jt=1,nt
+
+      zvol=0.d0
+      zsum=0.d0
+
+      DO jk = 1,nvpk
+         ik = jk+kmin-1
+         ! Get velocities v at ik
+!         zv(:,:)= getvar(cfilev, cvar,  ik ,npiglo,npjglo,kimin=imin,kjmin=jmin)
+          zv(:,:)= getvar(cfilev, cvar,  ik ,npiglo,npjglo,kimin=imin,kjmin=jmin,ktime=jt)
+          !!
+          !!LB:
+          !IF ( l_treat_ssh ) zv(:,npjglo) = zv(:,npjglo-1)
+          !!LB.
+          !!
+
+         zmask(:,:)=getvar(cmask,cvmask,ik,npiglo,npjglo,kimin=imin,kjmin=jmin)
+         !    zmask(:,npjglo)=0.  
+         ! get e3 at level ik ( ps...)
+         e3(:,:) = getvar(coordzgr, ce3, ik,npiglo,npjglo,kimin=imin,kjmin=jmin, ldiom=.TRUE.)
+         !
+         !LB:
+         WHERE ( zmask == 0. ) zv = 0. ! avoid problem with earth processors that have masked values
+         !LB.
+         ! 
+         !!
+         zsurf=SUM(e1 * e2 * zmask)
+         zvol2d=SUM(e1 * e2 * e3 * zmask)
+         zvol=zvol+zvol2d
+         zsum2d=SUM(zv*e1*e2*e3*zmask)
+         zsum=zsum+zsum2d
+         IF (zvol2d /= 0 )THEN
+            WRITE(16,*)' Mean value at level ',ik,'(',gdep(ik),' m) ',zsum2d/zvol2d, 'surface = ',zsurf/1.e6,' km^2'
+            !WRITE(numout,9004) gdep(ik), ik, zsum2d/zvol2d
+            WRITE(numout,*) jt, zsum2d/zvol2d, gdep(ik), ik
+            !IF (lwrtcdf) meanout(jk)=zsum2d/zvol2d
+            year_mean(jk) = zsum2d/zvol2d !LB
+            !!
+         ELSE
+            WRITE(16,*) ' No points in the water at level ',ik,'(',gdep(ik),' m) '
+            year_mean(jk) = 0.
+            IF (lwrtcdf) meanout(jk)=99999.
+         ENDIF
+      END DO
+      WRITE(16,*) ' Mean value over the ocean: ', zsum/zvol, jt
+      threedmeanout=zsum/zvol
+   END DO
+   CLOSE(numout)
+9004 FORMAT(f9.2,' ',i2,' ',f9.2)
+
+   CLOSE(16)
+   !LB.
+
+   
+   !LB:
+   IF ( l_pvp ) THEN
+      cf_out = trim(cvar)//'_mean_vert_profile.dat'
+      OPEN(14, FILE=cf_out)
+      DO jk = 1,nvpk
+         ik = jk+kmin-1
+         WRITE(14,*) gdep(ik), year_mean(ik)
+      END DO
+      CLOSE(14)
+   END IF
+   !LB.
+
+   IF(lwrtcdf) THEN
+      
+      !LB:
+      cfileoutnc=trim(cvar)//'_cdfmean.nc'
+      !LB.
+      
+      ! create output fileset
+      ncout =create(cfileoutnc,'none',kx,ky,npk,cdep=cdep)
+      ierr= createvar(ncout,typvar,nvars,ipk,id_varout )
+      ierr= putheadervar(ncout, cfilev ,kx, &
+           ky,npk,pnavlon=dumlon,pnavlat=dumlat,pdep=gdep,cdep=cdep)
+      tim=getvar1d(cfilev,'time_counter',1)
+      ierr=putvar1d(ncout,tim,1,'T')
+
+      ! netcdf output 
+      DO jk=1, nvpk
+         dummymean(1,1)=meanout(jk)
+         ierr = putvar(ncout, id_varout(1), dummymean, jk, kx, ky )
+      END DO
+
+      ierr=putvar0d(ncout,id_varout(2), threedmeanout )
+
+      ierr = closeout(ncout)
+
+   ENDIF
+
+ END PROGRAM cdfmean

+ 186 - 0
cdftools_light/src/cdfmeanvar.f90

@@ -0,0 +1,186 @@
+PROGRAM cdfmeanvar
+  !!-------------------------------------------------------------------
+  !!               ***  PROGRAM cdfmeanvar  ***
+  !!
+  !!  **  Purpose  :  Compute the Mean Value and variance  over the ocean
+  !!                  PARTIAL STEPS
+  !!  
+  !!  **  Method   :  compute the sum ( V * e1 *e2 * e3 *mask )/ sum( e1 * e2 * e3 *mask )
+  !!
+  !!
+  !! history ;
+  !!  Original :  J.M. Molines (Oct. 2005) 
+  !!              J.M. Molines  Add variance Nov. 2006
+  !!-------------------------------------------------------------------
+  !!  $Rev: 256 $
+  !!  $Date: 2009-07-21 17:49:27 +0200 (Tue, 21 Jul 2009) $
+  !!  $Id: cdfmeanvar.f90 256 2009-07-21 15:49:27Z molines $
+  !!--------------------------------------------------------------
+  !! * Modules used
+  USE cdfio
+
+  !! * Local variables
+  IMPLICIT NONE
+  INTEGER   :: jk, ik, jt
+  INTEGER   :: imin=0, imax=0, jmin=0, jmax=0      !: domain limitation for computation
+  INTEGER   :: kmin=0, kmax=0                      !: domain limitation for computation
+  INTEGER   :: ierr                                !: working integer
+  INTEGER   :: narg, iargc                         !: command line 
+  INTEGER   :: npiglo,npjglo,npk,nt                !: size of the domain
+  INTEGER   :: nvpk                                !: vertical levels in working variable
+
+  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=8)      :: zvol, zsum, zvol2d, zsum2d, zsurf, zvar, zvar2d
+  CHARACTER(LEN=256) :: cfilev , cdum, ctim
+  CHARACTER(LEN=256) :: coordhgr='mesh_hgr.nc',  coordzgr='mesh_zgr.nc',cmask='mask.nc'
+  CHARACTER(LEN=256) :: cvar, cvartype
+  CHARACTER(LEN=20) :: ce1, ce2, ce3, cvmask, cvtype, cdep
+
+  INTEGER    :: istatus
+
+  ! constants
+
+  !!  Read command line and output usage message if not compliant.
+  narg= iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' Usage : cdfmeanvar  ncfile cdfvar T| U | V | F | W [imin imax jmin jmax kmin kmax] '
+     PRINT *,' Computes the mean value, and the spatial variance of the field (3D, weighted) '
+     PRINT *,' imin imax jmin jmax kmin kmax can be given in option '
+     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 *,' PARTIAL CELLS VERSION'
+     PRINT *,' Files mesh_hgr.nc, mesh_zgr.nc ,mask.nc '
+     PRINT *,'  must be in the current directory'
+     PRINT *,' Output on standard output'
+     STOP
+  ENDIF
+
+  CALL getarg (1, cfilev)
+  CALL getarg (2, cvar)
+  CALL getarg (3, cvartype)
+
+  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 imin imax jmin jmax
+      CALL getarg ( 4,cdum) ; READ(cdum,*) imin
+      CALL getarg ( 5,cdum) ; READ(cdum,*) imax
+      CALL getarg ( 6,cdum) ; READ(cdum,*) jmin
+      CALL getarg ( 7,cdum) ; READ(cdum,*) jmax
+      CALL getarg ( 8,cdum) ; READ(cdum,*) kmin
+      CALL getarg ( 9,cdum) ; READ(cdum,*) kmax
+    ENDIF
+  ENDIF
+
+  npiglo= getdim (cfilev,'x')
+  npjglo= getdim (cfilev,'y')
+  npk   = getdim (cfilev,'depth')
+  nvpk  = getvdim(cfilev,cvar)
+
+  ctim = 'none'
+  nt    = getdim (cfilev,'time',cdtrue=ctim,kstatus=istatus) !LB
+
+  IF (imin /= 0 ) THEN ; npiglo=imax -imin + 1;  ELSE ; imin=1 ; ENDIF
+  IF (jmin /= 0 ) THEN ; npjglo=jmax -jmin + 1;  ELSE ; jmin=1 ; ENDIF
+  IF (kmin /= 0 ) THEN ; npk   =kmax -kmin + 1;  ELSE ; kmin=1 ; ENDIF
+
+  IF (nvpk == 2 ) nvpk = 1
+  IF (nvpk == 3 ) nvpk = npk
+
+  PRINT *, 'npiglo=', npiglo
+  PRINT *, 'npjglo=', npjglo
+  PRINT *, 'npk   =', npk
+  PRINT *, 'nvpk  =', nvpk
+  PRINT *, 'nt    =', nt
+
+  IF ((npk .EQ. 0) .AND. (nt .GT. 1)) THEN
+     npk=1
+     PRINT *, 'W A R N I N G : you used a forcing field'
+  END IF
+  ! Allocate arrays
+  ALLOCATE ( zmask(npiglo,npjglo) )
+  ALLOCATE ( zv(npiglo,npjglo) )
+  ALLOCATE ( e1(npiglo,npjglo),e2(npiglo,npjglo), e3(npiglo,npjglo) )
+  ALLOCATE ( gdep(npk) )
+  SELECT CASE (TRIM(cvartype))
+  CASE ( 'T' )
+     ce1='e1t'
+     ce2='e2t'
+     ce3='e3t_0'
+     cvmask='tmask'
+     cdep='gdept'
+  CASE ( 'U' )
+     ce1='e1u'
+     ce2='e2u'
+     ce3='e3t_0'
+     cvmask='umask'
+     cdep='gdept'
+  CASE ( 'V' )
+     ce1='e1v'
+     ce2='e2v'
+     ce3='e3t_0'
+     cvmask='vmask'
+     cdep='gdept'
+  CASE ( 'F' )
+     ce1='e1f'
+     ce2='e2f'
+     ce3='e3t_0'
+     cvmask='fmask'
+     cdep='gdept'
+  CASE ( 'W' )
+     ce1='e1t'
+     ce2='e2t'
+     ce3='e3w_0'
+     cvmask='tmask'
+     cdep='gdepw'
+  CASE DEFAULT
+      PRINT *, 'this type of variable is not known :', trim(cvartype)
+      STOP
+  END SELECT
+
+  e1(:,:) = getvar(coordhgr, ce1, 1,npiglo,npjglo,kimin=imin,kjmin=jmin)
+  e2(:,:) = getvar(coordhgr, ce2, 1,npiglo,npjglo,kimin=imin,kjmin=jmin)
+  gdep(:) = getvare3(coordzgr,cdep,npk)
+
+  zvol=0.d0
+  zsum=0.d0
+  DO jt = 1,nt
+     DO jk = 1,nvpk
+        ik = jk+kmin-1
+        ! Get velocities v at ik
+        zv(:,:)= getvar(cfilev, cvar,  ik ,npiglo,npjglo,kimin=imin,kjmin=jmin, ktime=jt)
+        IF ( nvpk /= 1 .OR. jt == 1 ) THEN
+          ! if there is only one level do not read mask and e3 every time step ...
+          zmask(:,:)=getvar(cmask,cvmask,ik,npiglo,npjglo,kimin=imin,kjmin=jmin)
+          ! get e3 at level ik ( ps...)
+          e3(:,:) = getvar(coordzgr, ce3, ik,npiglo,npjglo,kimin=imin,kjmin=jmin, ldiom=.true.)
+        END IF
+        ! 
+        zsurf=sum(e1 * e2 * zmask)
+        zvol2d=sum(e1 * e2 * e3 * zmask)
+        zvol=zvol+zvol2d
+        zsum2d=sum(zv*e1*e2*e3*zmask)
+        zvar2d=sum(zv*zv*e1*e2*e3*zmask)
+        zsum=zsum+zsum2d
+        zvar=zvar+zvar2d
+        IF (zvol2d /= 0 )THEN
+           PRINT *, ' Mean value at level ',ik,'(',gdep(ik),' m) ',zsum2d/zvol2d, 'surface = ',zsurf/1.e6,' km^2 jt=', jt 
+           PRINT *, ' Mean value2 at level ',ik,'(',gdep(ik),' m) ',zvar2d/zvol2d, 'variance=', &
+                &    zvar2d/zvol2d - (zsum2d/zvol2d)*(zsum2d/zvol2d)
+        ELSE
+           PRINT *, ' No points in the water at level ',ik,'(',gdep(ik),' m) '
+        ENDIF
+     END DO
+  END DO
+
+  PRINT * ,' Mean value over the ocean: ', zsum/zvol
+  PRINT * ,' Global variance over the ocean: ', zvar/zvol - (zsum/zvol)*(zsum/zvol)
+  PRINT * ,' Global std dev over the ocean: ', sqrt(zvar/zvol - (zsum/zvol)*(zsum/zvol))
+  
+END PROGRAM cdfmeanvar

+ 358 - 0
cdftools_light/src/cdfmhst.f90

@@ -0,0 +1,358 @@
+PROGRAM cdfmhst
+
+  !!--------------------------------------------------------------------
+  !!               ***  PROGRAM  cdfmhst  ***
+  !!
+  !!  **  Purpose  : Compute Meridional Heat Salt  Transport.
+  !!
+  !!  **  Method   : Starts from the mean VT, VS fields computed by cdfvT
+  !!                 The program looks for the file "new_maskglo.nc". If it does not exist,
+  !!                 only the calculation over all the domain is performed (this is adequate
+  !!                 for a basin configuration like NATL4).
+  !!
+  !!
+  !! history :
+  !!      Original : J.M. Molines (jan. 2005)
+  !!                 J.M. Molines apr. 2005 : use modules
+  !!                 A.M. Treguier (april 2006) adaptation to NATL4 case
+  !!                 J.M. Molines ( April 2007) : add netcdf output
+  !!--------------------------------------------------------------------
+  !!  $Rev: 298 $
+  !!  $Date: 2010-04-14 18:09:06 +0200 (Wed, 14 Apr 2010) $
+  !!  $Id: cdfmhst.f90 298 2010-04-14 16:09:06Z dussin9r $
+  !!--------------------------------------------------------------
+
+  USE netcdf
+
+  !! * Modules used
+  USE cdfio
+
+  !! * Local variables
+  IMPLICIT NONE
+
+  INTEGER   :: jj,jk,jt                         !: dummy loop index
+  INTEGER   :: narg, iargc                      !: command line
+  INTEGER   :: npiglo, npjglo, npk, Nt          !: size of the domain
+  INTEGER   :: numout = 10
+  INTEGER, DIMENSION(2)          ::  iloc
+  LOGICAL    :: llglo = .false.                !: indicator for presence of new_maskglo.nc file
+
+  LOGICAL :: lfncout = .false.
+
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: e1v, e3v ,gphiv, zvt, zvs !: mask, metrics
+
+  REAL(KIND=4), DIMENSION(:,:,:), ALLOCATABLE ::  zmask
+
+  REAL(KIND=4), DIMENSION (:,:),     ALLOCATABLE ::  dumlon              !: dummy longitude = 0.
+  REAL(KIND=4), DIMENSION (:,:),     ALLOCATABLE ::  dumlat              !: latitude for i = north pole
+
+  REAL(KIND=4), DIMENSION (:),       ALLOCATABLE ::  tim       !LB
+
+  REAL(KIND=8), DIMENSION (:,:),   ALLOCATABLE :: zwkt, zwks
+  REAL(KIND=8), DIMENSION (:,:,:), ALLOCATABLE :: ztrpt, ztrps !LB
+
+  REAL(KIND=8) ,DIMENSION(:,:) , ALLOCATABLE ::  vmerid_heat, vmerid_salt
+  REAL(KIND=8) ,DIMENSION(:)   , ALLOCATABLE ::  vback_1d
+
+  REAL(KIND=8) ,DIMENSION(:,:) , ALLOCATABLE ::  merid_heat_glo, merid_heat_atl, merid_heat_pac,&
+       &                                       merid_heat_ind, merid_heat_inp
+  REAL(KIND=8) ,DIMENSION(:,:) , ALLOCATABLE ::  merid_salt_glo, merid_salt_atl, merid_salt_pac,&
+       &                                       merid_salt_ind, merid_salt_inp, zmtrp
+
+  CHARACTER(LEN=256) :: cfileVT
+
+  CHARACTER(LEN=256), PARAMETER :: cfileout='merid_heat_trp.dat', cfileouts='merid_salt_trp.dat'
+
+  ! to be put in namelist eventually
+  CHARACTER(LEN=256) :: cf_mm='mesh_mask.nc', cf_bm='new_maskglo.nc'
+
+  ! NC output
+  INTEGER            :: jbasin, js, jvar   !: dummy loop index
+  INTEGER            :: nbasins, ierr
+
+  REAL(KIND=4), PARAMETER :: rpspval=9999.99
+  REAL(KIND=4), DIMENSION(1) :: gdep
+  
+  CHARACTER(LEN=256) :: cdum, ctim
+  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE   :: vcv_name_t, vcv_name_s   !: array of var name for input
+  CHARACTER(LEN=4),   DIMENSION(4) :: cbasin= (/ '_GLO','_atl','_pac','_ind' /)
+
+  ! constants
+  REAL(KIND=4),PARAMETER   ::  rau0=1000.,   rcp=4000.
+
+
+  CHARACTER(LEN=64) :: cv_out = 'mht', cv_dum
+  CHARACTER(LEN=1024) :: cf_out = 'mht_1d.nc'
+  INTEGER :: idf_out, idd_y, idv_lat, idd_t, idv_time, jt_pos
+
+  INTEGER, DIMENSION(5) :: vid_heat, vid_salt
+  REAL :: ryear
+  REAL, PARAMETER :: rmissing = -9999.
+
+
+  !!  Read command line and output usage message if not compliant.
+  narg= iargc()
+  IF ( narg /= 3 ) THEN
+     PRINT *,' Usage : cdfmhst  <VTfile> <file_output.nc> <year>'
+     PRINT *,' Files mesh_mask.nc and new_maskglo.nc must be in te current directory'
+     PRINT *,' NetCDF Output in <file_output.nc> with variables :'
+     PRINT *,'                       zomht_glo, zomht_atl, zomht_inp, zomht_pac'
+     PRINT *,'                       zomst_glo, zomst_atl, zomst_inp, zomst_pac'
+     STOP
+  ENDIF
+
+  CALL getarg(1, cfileVT)
+  CALL getarg(2, cf_out)
+  CALL getarg(3,cdum)    ; READ(cdum,*) ryear
+
+
+
+
+  npiglo= getdim (cfileVT,'x')
+  npjglo= getdim (cfileVT,'y')
+  npk   = getdim (cfileVT,'depth')
+
+  ctim = 'none'
+  Nt    = getdim (cfileVT,'time', cdtrue=ctim) !LB
+
+  !LB:
+  IF (Nt == 0) THEN
+     PRINT *, 'Nt=0, assume 1' ; Nt = 1
+  END IF
+  !LB.
+
+
+
+  PRINT *, 'npiglo=', npiglo
+  PRINT *, 'npjglo=', npjglo
+  PRINT *, 'npk   =', npk
+  PRINT *, 'Nt    =', Nt
+
+  ! Allocate arrays
+  ALLOCATE ( zwkt(npiglo,npjglo), zmask(npiglo,npjglo,5), zvt(npiglo,npjglo) )
+  ALLOCATE ( zwks(npiglo,npjglo) ,zvs(npiglo,npjglo) )
+  ALLOCATE ( e1v(npiglo,npjglo),e3v(npiglo,npjglo), gphiv(npiglo,npjglo) )
+  ALLOCATE ( ztrpt(npiglo,npjglo,Nt) , ztrps(npiglo,npjglo,Nt) )
+  ALLOCATE ( vmerid_heat(npjglo,5), vmerid_salt(npjglo,5), vback_1d(npjglo) )
+  ALLOCATE ( merid_heat_glo(npjglo,Nt), merid_heat_atl(npjglo,Nt), merid_heat_pac(npjglo,Nt) )
+  ALLOCATE ( merid_heat_ind(npjglo,Nt), merid_heat_inp(npjglo,Nt) )
+  ALLOCATE ( merid_salt_glo(npjglo,Nt), merid_salt_atl(npjglo,Nt), merid_salt_pac(npjglo,Nt) )
+  ALLOCATE ( merid_salt_ind(npjglo,Nt), merid_salt_inp(npjglo,Nt) )
+  ALLOCATE ( zmtrp(npjglo,Nt) )
+  ALLOCATE ( dumlon(1,npjglo) , dumlat(1,npjglo))
+  ALLOCATE ( tim(Nt) )
+
+
+
+
+  ! create output fileset
+  e1v(:,:)   = getvar(cf_mm, 'e1v', 1,npiglo,npjglo)
+  gphiv(:,:) = getvar(cf_mm, 'gphiv', 1,npiglo,npjglo)
+  gdep(:)    = getvare3(cf_mm, 'nav_lev' ,1)
+
+  iloc=maxloc(gphiv)
+  dumlat(1,:) = gphiv(iloc(1),:)
+  dumlon(:,:) = 0.   ! set the dummy longitude to 0
+
+
+
+  ztrpt(:,:,:)= 0
+  ztrps(:,:,:)= 0
+
+
+  DO jt = 1, Nt !LB
+
+     DO jk = 1,npk
+
+        ! Get temperature and salinity at jk
+        zvt(:,:) = getvar(cfileVT, 'vomevt', jk, npiglo,npjglo, ktime=jt)  !LB
+        zvs(:,:) = getvar(cfileVT, 'vomevs', jk, npiglo,npjglo, ktime=jt)  !LB
+
+        ! get e3v at level jk
+        e3v(:,:)  = getvar(cf_mm, 'e3v_0', jk,npiglo,npjglo, ldiom=.true.)
+        zwkt(:,:) = zvt(:,:)*e1v(:,:)*e3v(:,:)
+        zwks(:,:) = zvs(:,:)*e1v(:,:)*e3v(:,:)
+
+        ! integrates vertically
+        ztrpt(:,:,jt) = ztrpt(:,:,jt) + zwkt(:,:)*rau0*rcp
+        ztrps(:,:,jt) = ztrps(:,:,jt) + zwks(:,:)
+
+     END DO  ! jk
+
+
+     ! ~~~~~~
+     ! global
+     ! ~~~~~~~
+     IF ( jt == 1 ) zmask(:,:,1) = getvar(cf_mm, 'vmask', 1, npiglo, npjglo) !LB
+
+     DO jj=1,npjglo
+        merid_heat_glo(jj,jt) = SUM( ztrpt(2:npiglo-1,jj,jt)*zmask(2:npiglo-1,jj,1) )
+        merid_salt_glo(jj,jt) = SUM( ztrps(2:npiglo-1,jj,jt)*zmask(2:npiglo-1,jj,1) )
+     END DO
+
+
+  END DO ! jt
+
+
+
+
+  !  Detects newmaskglo file
+  INQUIRE( FILE=cf_bm, EXIST=llglo )
+
+  nbasins=1         ! 1 basin (Global)
+  IF ( llglo )  nbasins=4 ! 4 basins (Global, Pacific, Atlantic, Inidan)
+  
+  ! Allocate output variables
+  ALLOCATE(vcv_name_t(nbasins), vcv_name_s(nbasins))
+
+
+
+  PRINT *, ''
+
+  IF ( llglo ) THEN
+
+     DO jt = 1, Nt !LB
+
+        ! Merid mean with mask
+
+        ! Atlantic
+        IF ( jt == 1 ) zmask(:,:,2) = getvar(cf_bm,'tmaskatl',1,npiglo,npjglo)
+
+        DO jj=1,npjglo
+           merid_heat_atl(jj,jt) = SUM( ztrpt(:,jj,jt)*zmask(:,jj,2) )
+           merid_salt_atl(jj,jt) = SUM( ztrps(:,jj,jt)*zmask(:,jj,2) )
+        END DO
+
+
+        ! Pacific
+        IF ( jt == 1 ) zmask(:,:,3) = getvar(cf_bm,'tmaskpac',1,npiglo,npjglo)
+
+        DO jj=1,npjglo
+           merid_heat_pac(jj,jt)= SUM( ztrpt(:,jj,jt)*zmask(:,jj,3) )
+           merid_salt_pac(jj,jt)= SUM( ztrps(:,jj,jt)*zmask(:,jj,3) )
+        END DO
+
+
+        ! Indian
+        IF ( jt == 1 ) zmask(:,:,4) = getvar(cf_bm,'tmaskind',1,npiglo,npjglo)
+
+        DO jj=1,npjglo
+           merid_heat_ind(jj,jt)= SUM( ztrpt(:,jj,jt)*zmask(:,jj,4) )
+           merid_salt_ind(jj,jt)= SUM( ztrps(:,jj,jt)*zmask(:,jj,4) )
+        END DO
+
+     END DO
+
+  END IF
+
+
+
+  tim  = getvar1d(cfileVT, trim(ctim), Nt) !LB: nt
+
+
+  !! Plotting annually-averaged profiles:  !LB
+  !! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+  DO jj = 1, npjglo
+
+     vmerid_heat(jj,1) = SUM(merid_heat_glo(jj,:))/Nt/1e15
+     vmerid_heat(jj,2) = SUM(merid_heat_atl(jj,:))/Nt/1e15
+     vmerid_heat(jj,3) = SUM(merid_heat_pac(jj,:))/Nt/1e15
+     vmerid_heat(jj,4) = SUM(merid_heat_ind(jj,:))/Nt/1e15
+
+     vmerid_salt(jj,1) = SUM(merid_salt_glo(jj,:))/Nt/1e6
+     vmerid_salt(jj,2) = SUM(merid_salt_atl(jj,:))/Nt/1e6
+     vmerid_salt(jj,3) = SUM(merid_salt_pac(jj,:))/Nt/1e6
+     vmerid_salt(jj,4) = SUM(merid_salt_ind(jj,:))/Nt/1e6
+
+     IF ( (vmerid_salt(jj,2) == 0.0).AND.(jj > 20) ) THEN
+        vmerid_salt(jj,4) = 0.0
+        vmerid_salt(jj,5) = 0.0
+     END IF
+     IF ( (vmerid_heat(jj,2) == 0.0).AND.(jj > 20) ) THEN
+        vmerid_heat(jj,4) = 0.0
+        vmerid_heat(jj,5) = 0.0
+     END IF
+
+  END DO
+
+  !! WTF:
+  WHERE ( vmerid_heat == 0.0 ) vmerid_heat = rmissing
+  WHERE ( vmerid_salt == 0.0 ) vmerid_salt = rmissing
+
+
+
+
+
+
+  DO jbasin = 1, nbasins
+     vcv_name_t(jbasin) = 'zomht'//TRIM(cbasin(jbasin))
+     vcv_name_s(jbasin) = 'zomst'//TRIM(cbasin(jbasin))
+  END DO
+
+
+  !
+
+
+  !! LOLO netcdf
+  INQUIRE( FILE=cf_out, EXIST=lfncout )
+
+
+  IF ( .NOT. lfncout ) THEN
+
+     !! Creating file
+     PRINT *, ' Creating file '//trim(cf_out)//' !!!'
+     ierr = NF90_CREATE(cf_out, NF90_CLOBBER, idf_out)
+     ierr = NF90_DEF_DIM(idf_out, 'y',   npjglo, idd_y) !
+     ierr = NF90_DEF_VAR(idf_out, 'lat', NF90_FLOAT, idd_y, idv_lat)
+     ierr = NF90_DEF_DIM(idf_out, 'time', NF90_UNLIMITED, idd_t)
+     ierr = NF90_DEF_VAR(idf_out, 'time', NF90_DOUBLE,    idd_t, idv_time)
+
+     DO jbasin = 1, nbasins
+        ierr = NF90_DEF_VAR(idf_out, trim(vcv_name_t(jbasin)), NF90_FLOAT, (/idd_y,idd_t/), vid_heat(jbasin))
+        ierr = NF90_PUT_ATT(idf_out, vid_heat(jbasin), '_FillValue', rmissing)        
+        ierr = NF90_DEF_VAR(idf_out, TRIM(vcv_name_s(jbasin)), NF90_FLOAT, (/idd_y,idd_t/), vid_salt(jbasin))
+        ierr = NF90_PUT_ATT(idf_out, vid_salt(jbasin), '_FillValue', rmissing)
+     END DO
+
+     ierr = NF90_ENDDEF(idf_out)
+     ierr = NF90_PUT_VAR(idf_out, idv_lat,  dumlat(1,:))
+     jt_pos = 0
+  ELSE
+
+     !! Opening already existing file
+     ierr = NF90_OPEN  (cf_out, NF90_WRITE,   idf_out)
+
+     !! Need IDs of variables to append... NF90_INQ_VARID
+     DO jbasin = 1, nbasins
+        ierr = NF90_INQ_VARID(idf_out, trim(vcv_name_t(jbasin)), vid_heat(jbasin))
+        ierr = NF90_INQ_VARID(idf_out, trim(vcv_name_s(jbasin)), vid_salt(jbasin))
+     END DO
+
+
+     ! Get ID of unlimited dimension
+     ierr = NF90_INQUIRE(idf_out, unlimitedDimId = idv_time)
+
+     ! Need to know jt_pos, record number of the last time record writen in the file
+     ierr = NF90_INQUIRE_DIMENSION(idf_out, idv_time, name=cv_dum, len=jt_pos)
+     !PRINT *, 'cv_dum, jt_pos = ', trim(cv_dum), jt_pos
+  END IF
+
+  WRITE(*,'("Going to write record #",i4.4," into ",a)') jt_pos+1, trim(cf_out)
+
+  !DO jt = 1, Nt
+  jt = 1 ! saving 1 record per year!
+
+  ! Writing record jt for time vector and 1d fields:
+  ierr = NF90_PUT_VAR( idf_out, idv_time, (/ryear+0.5/), start=(/jt_pos+jt/), count=(/1/) )
+
+  DO jbasin = 1, nbasins
+     ierr = NF90_PUT_VAR(idf_out, vid_heat(jbasin), vmerid_heat(:,jbasin), start=(/1,jt_pos+jt/), count=(/npjglo,1/))
+     ierr = NF90_PUT_VAR(idf_out, vid_salt(jbasin), vmerid_salt(:,jbasin), start=(/1,jt_pos+jt/), count=(/npjglo,1/))
+  END DO
+  !END DO
+
+  ierr = NF90_PUT_ATT(idf_out, NF90_GLOBAL, 'About', 'Created by BaraKuda (cdfmhst.f90) => https://github.com/brodeau/barakuda')
+  ierr = NF90_CLOSE(idf_out)
+
+END PROGRAM cdfmhst

+ 290 - 0
cdftools_light/src/cdfmoc.f90

@@ -0,0 +1,290 @@
+PROGRAM cdfmoc
+   !!-------------------------------------------------------------------
+   !!               ***  PROGRAM cdfmoc  ***
+   !!
+   !!  **  Purpose  :  Compute the Meridional Overturning Cell (MOC)
+   !!                  PARTIAL STEPS
+   !!
+   !!  **  Method   :  The MOC is computed from the V velocity field, integrated
+   !!                  from the bottom to the surface, then zonally averaged with
+   !!                  eventual masking for oceanic basins.
+   !!                  The program looks for the file "new_maskglo.nc". If it does not exist,
+   !!                  only the calculation over all the domain is performed (this is adequate
+   !!                  for a basin configuration like NATL4).
+   !!                  In new_maskglo.nc the masking corresponds to the global
+   !!                  configuration. MOC for Global, Atlantic, Indo-Pacific, Indian,Pacific ocean
+   !!                  Results are saved on moc.nc file with variables name respectively
+   !!                  zomsfglo, zomsfatl, zomsfinp, zomsfind, zomsfpac
+   !!
+   !!
+   !! history ;
+   !!  Original :  J.M. Molines  (jul.  2005)
+   !!              A.M. Treguier (april 2006) adaptation to NATL4 case
+   !!-------------------------------------------------------------------
+   !!  $Rev: 256 $
+   !!  $Date: 2009-07-21 17:49:27 +0200 (Tue, 21 Jul 2009) $
+   !!  $Id: cdfmoc.f90 256 2009-07-21 15:49:27Z molines $
+   !!--------------------------------------------------------------
+   !! * Modules used
+
+   USE cdfio
+   USE io_ezcdf
+
+   !! * Local variables
+   IMPLICIT NONE
+   INTEGER   :: jpbasins
+   INTEGER   :: jbasin, jj, jk ,ji, jt              !: dummy loop index
+   INTEGER   :: ierr                                !: working integer
+   INTEGER   :: narg, iargc                         !: command line
+   INTEGER   :: npiglo,npjglo, npk, nt              !: size of the domain
+   INTEGER   :: ncout, np
+   INTEGER   :: numout=10
+   INTEGER, DIMENSION(:), ALLOCATABLE ::  ipk, id_varout         !
+   INTEGER, DIMENSION(2)              ::  iloc
+
+   !REAL(KIND=4), DIMENSION (:,:),     ALLOCATABLE ::  e1v, e3v, gphiv, zv !:  metrics, velocity
+   REAL(KIND=4), DIMENSION (:,:),     ALLOCATABLE ::  e1v, gphiv, zv !:  metrics, velocity
+   REAL(KIND=4), DIMENSION (:,:,:),   ALLOCATABLE ::  e3v, V_3D, Veiv_3D
+   REAL(KIND=4), DIMENSION (:,:),     ALLOCATABLE ::  dumlon              !: dummy longitude = 0.
+   REAL(KIND=4), DIMENSION (:,:),     ALLOCATABLE ::  dumlat              !: latitude for i = north pole
+   REAL(KIND=4), DIMENSION (:),       ALLOCATABLE ::  gdepw               !: deptw
+   REAL(KIND=4), DIMENSION (:,:,:),   ALLOCATABLE ::  zmask               !:  jpbasins x npiglo x npjglo
+   REAL(KIND=4), DIMENSION (:),       ALLOCATABLE ::  tim       !LB
+
+   REAL(KIND=8) ,DIMENSION(:,:,:) ,   ALLOCATABLE ::  zomsf                 !: jpbasins x npjglo x npk
+
+   CHARACTER(LEN=256) :: cf_v , cf_out='moc.nc', ctim, cv_v, cv_veiv
+
+   CHARACTER(LEN=256) :: cf_mm='mesh_mask.nc', cf_bm='new_maskglo.nc'
+   TYPE(variable)    ,DIMENSION(:), ALLOCATABLE   :: typvar                   !: structure for attribute
+
+   LOGICAL    :: llglo = .false., & !: indicator for presence of new_maskglo.nc file
+      &        leiv  = .FALSE.    !: weather to use Eddy Induced velocity from GM90
+
+   INTEGER :: istatus
+   INTEGER :: idf_0, idv_0, idf_v, idv_v, idf_veiv, idv_veiv
+   LOGICAL :: lmv               ! to check on missing values
+   REAL(4) :: missing_value
+
+   ! constants
+
+   !!  Read command line and output usage message if not compliant.
+   narg= iargc()
+   IF ( (narg < 2).OR.(narg > 3) ) THEN
+      PRINT *,' Usage : cdfmoc  <V file> <V variable> (<Veiv variable>)'
+      PRINT *,' Computes the MOC for oceanic basins as described in new_maskglo.nc'
+      PRINT *,' PARTIAL CELLS VERSION'
+      PRINT *,' Files mesh_mask.nc and new_maskglo.nc '
+      PRINT *,'  must be in the current directory'
+      PRINT *,' Output on moc.nc: '
+      PRINT *,'      variables zomsfglo  : Global ocean '
+      PRINT *,'      variables zomsfatl  : Atlantic Ocean '
+      PRINT *,'      variables zomsfinp  : Indo Pacific '
+      PRINT *,'      variables zomsfind  : Indian Ocean alone'
+      PRINT *,'      variables zomsfpac  : Pacific Ocean alone'
+      STOP
+   ENDIF
+
+   CALL getarg (1, cf_v)
+   CALL getarg (2, cv_v)
+
+   PRINT *, ' Will compute MOC using '//trim(cv_v)//' !!!'
+
+   leiv = .FALSE.
+   IF (narg == 3) THEN
+      CALL getarg (3, cv_veiv)
+      IF ( trim(cv_veiv) /= '0' ) THEN
+         leiv = .TRUE.
+         PRINT *, ' and taking eddy-induced velocity into account using '//trim(cv_veiv)//' !!!'
+      END IF
+   END IF
+
+
+   npiglo= getdim(cf_v,'x',ldexact=.TRUE.)
+   npjglo= getdim(cf_v,'y',ldexact=.TRUE.)
+   npk   = getdim(cf_v,'depthv')
+
+   ctim = 'none'
+   nt    = getdim (cf_v,'time',cdtrue=ctim,kstatus=istatus) !LB
+
+   !LB:
+   PRINT *, ''
+   PRINT *, 'npiglo =',npiglo
+   PRINT *, 'npjglo =',npjglo
+   PRINT *, 'npk    =',npk
+   PRINT *, 'nt     =',nt  !PM
+   PRINT *, ''
+   !LB.
+
+   !LB:
+   IF (nt == 0) THEN
+      PRINT *, 'nt=0, assume 1' ; nt = 1
+   END IF
+   !LB.
+
+
+
+
+   !  Detects newmaskglo file
+   INQUIRE( FILE=cf_bm, EXIST=llglo )
+   IF (llglo) THEN
+      jpbasins = 5
+      PRINT *, 'Basin file "new_maskglo.nc" found!'; PRINT *, ''
+   ELSE
+      jpbasins = 1
+   ENDIF
+
+   ALLOCATE ( typvar(jpbasins), ipk(jpbasins), id_varout(jpbasins) )
+
+   ! define new variables for output
+   typvar(1)%name= 'zomsfglo'
+   typvar%units='Sverdrup'
+   typvar%missing_value=99999.
+   typvar%valid_min= -1000.
+   typvar%valid_max= 1000.
+   typvar%scale_factor= 1.
+   typvar%add_offset= 0.
+   typvar%savelog10= 0.
+   typvar(1)%long_name='Meridional_Overt.Cell_Global'
+   typvar(1)%short_name='zomsfglo'
+   typvar%online_operation='N/A'
+   typvar%axis='TZY'
+
+   ipk(1) = npk  !  2D
+
+   IF (llglo) THEN
+      typvar(2)%name= 'zomsfatl'
+      typvar(2)%long_name='Meridional_Overt.Cell_Atlantic'
+      typvar(2)%short_name='zomsfatl'
+
+      typvar(3)%name= 'zomsfinp'
+      typvar(3)%long_name='Meridional_Overt.Cell_IndoPacif'
+      typvar(3)%short_name='zomsfinp'
+
+      typvar(4)%name= 'zomsfind'
+      typvar(4)%long_name='Meridional_Overt.Cell_Indian'
+      typvar(4)%short_name='zomsfind'
+
+      typvar(5)%name= 'zomsfpac'
+      typvar(5)%long_name='Meridional_Overt.Cell_pacif'
+      typvar(5)%short_name='zomspac'
+
+      ipk(2) = npk  !  2D
+      ipk(3) = npk  !  2D
+      ipk(4) = npk  !  2D
+      ipk(5) = npk  !  2D
+   ENDIF
+
+
+   ! Allocate arrays
+   ALLOCATE ( zmask(jpbasins,npiglo,npjglo) )
+   ALLOCATE ( zv(npiglo,npjglo) )
+   ALLOCATE ( e1v(npiglo,npjglo),e3v(npiglo,npjglo,npk), V_3D(npiglo,npjglo,npk), gphiv(npiglo,npjglo) ,gdepw(npk) )
+   ALLOCATE ( zomsf(jpbasins, npjglo, npk) )
+   ALLOCATE ( dumlon(1,npjglo) , dumlat(1,npjglo))
+   ALLOCATE ( tim(nt) )
+
+   IF ( leiv ) ALLOCATE ( Veiv_3D(npiglo,npjglo,npk) )
+
+
+   e1v(:,:)   = getvar  (cf_mm, 'e1v', 1,npiglo,npjglo)
+   gphiv(:,:) = getvar  (cf_mm, 'gphiv', 1,npiglo,npjglo)
+   !gdepw(:)  = getvare3(cf_mm, 'gdepw',npk)
+   gdepw(:)   = getvar1d(cf_mm, 'gdepw_1d',npk)
+   gdepw(:)   = -1.*  gdepw(:)
+
+
+
+   iloc=maxloc(gphiv)
+   dumlat(1,:) = gphiv(iloc(1),:)
+   dumlon(:,:) = 0.   ! set the dummy longitude to 0
+
+   ! create output fileset
+   ncout =create(cf_out, 'none', 1,npjglo,npk,cdep='depthw')
+   ierr= createvar(ncout ,typvar,jpbasins, ipk,id_varout )
+   ierr= putheadervar(ncout, cf_v,1, npjglo,npk,pnavlon=dumlon,pnavlat=dumlat,pdep=gdepw)
+
+   tim=getvar1d(cf_v,trim(ctim),nt) !LB: nt
+   ierr=putvar1d(ncout,tim,nt,'T') !LB: nt
+
+
+   ! reading the masks
+   ! 1 : global ; 2 : Atlantic ; 3 : Indo-Pacif ; 4 : Indian ; 5 : Pacif
+   zmask(1,:,:)=getvar(cf_mm,'vmask',1,npiglo,npjglo)
+   IF ( llglo ) THEN
+      zmask(2,:,:)=getvar(cf_bm,'tmaskatl',1,npiglo,npjglo)
+      zmask(4,:,:)=getvar(cf_bm,'tmaskind',1,npiglo,npjglo)
+      zmask(5,:,:)=getvar(cf_bm,'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
+      ! change global mask for GLOBAL periodic condition
+      zmask(1,1,:) = 0.
+      zmask(1,npiglo,:) = 0.
+   ENDIF
+
+
+
+
+   CALL GETVAR_3D(idf_0, idv_0, cf_mm, 'e3v_0', 0, 0, e3v) ; idf_0 = 0. ; idv_0 = 0.
+
+
+   ! retrieve missing_value if defined
+   CALL CHECK_4_MISS(cf_v, trim(cv_v), lmv, missing_value)
+
+   DO jt = 1, nt !LB
+
+      PRINT *, ' * [cdfmoc] jt = ', jt
+
+      ! read data and set missing values to 0
+      CALL GETVAR_3D(idf_v, idv_v,  cf_v, trim(cv_v), nt, jt, V_3D)
+      IF (lmv) THEN
+        WHERE(V_3D == missing_value) V_3D = 0.0
+      ENDIF
+        
+      IF ( leiv ) CALL GETVAR_3D(idf_veiv, idv_veiv,  cf_v, trim(cv_veiv), nt, jt, Veiv_3D)
+
+
+      ! initialize moc to 0
+      zomsf(:,:,:) = 0.
+
+      DO jk = 1,npk-1
+         ! Get velocities v at jk
+         !zv(:,:) =  getvar(cf_v, trim(cv_v), jk, npiglo, npjglo, ktime=jt)  !LB
+         zv(:,:) = V_3D(:,:,jk)
+
+         IF ( leiv ) zv(:,:) = zv(:,:) + Veiv_3D(:,:,jk)
+
+         ! integrates 'zonally' (along i-coordinate)
+         DO ji=1,npiglo
+            ! For all basins
+            DO jbasin = 1, jpbasins
+               DO jj=1,npjglo
+                  zomsf(jbasin,jj,jk) = zomsf(jbasin,jj,jk) &
+                     &              - e1v(ji,jj)*e3v(ji,jj,jk)*zmask(jbasin,ji,jj)*zv(ji,jj)
+               ENDDO
+            END DO
+         END DO
+      END DO
+
+      ! integrates vertically   from bottom to surface
+      DO jk=npk-1 , 1 , -1
+         zomsf(:,:,jk) = zomsf(:,:,jk+1) + zomsf(:,:,jk)/1.e6
+      END DO  ! loop to next level
+
+      ! netcdf output
+      DO jbasin= 1, jpbasins
+         DO jk =1, npk
+            ierr = putvar(ncout, id_varout(jbasin),REAL(zomsf(jbasin,:,jk)), jk,1,npjglo, jt) !LB
+            !ierr = putvar(ncout, id_varout(1)     ,rotn,                     1 ,npiglo, npjglo, jt)
+         END DO
+      END DO
+
+
+   END DO
+
+   ierr = closeout(ncout)
+
+   PRINT *, '  *** cdfmoc => '//TRIM(cf_out)//' written!'; PRINT *, ''
+
+END PROGRAM cdfmoc

+ 197 - 0
cdftools_light/src/cdfmoy.f90

@@ -0,0 +1,197 @@
+PROGRAM cdfmoy
+  !!-----------------------------------------------------------------------
+  !!                 ***  PROGRAM cdfmoy  ***
+  !!
+  !!  **  Purpose: Compute mean values for all the variables in a bunch
+  !!                of cdf files given as argument
+  !!                Store the results on a 'similar' cdf file.
+  !!  
+  !!  **  Method: Try to avoid 3 d arrays 
+  !!
+  !! history :
+  !!     Original code :   J.M. Molines (Nov 2004 ) for ORCA025
+  !!                       J.M. Molines (Apr 2005 ) put all NCF stuff in module
+  !!                              now valid for grid T U V W icemod
+  !!     Modified      :   P. Mathiot (June 2007) update for forcing fields
+  !!-----------------------------------------------------------------------
+  !!  $Rev: 321 $
+  !!  $Date: 2010-05-20 06:46:20 +0200 (Thu, 20 May 2010) $
+  !!  $Id: cdfmoy.f90 321 2010-05-20 04:46:20Z molines $
+  !!--------------------------------------------------------------
+  !!
+  USE cdfio 
+
+  IMPLICIT NONE
+  INTEGER   :: jk,jt,jvar, jv , jtt,jkk                     !: dummy loop index
+  INTEGER   :: ierr                                         !: working integer
+  INTEGER   :: narg, iargc                                  !: 
+  INTEGER   :: npiglo,npjglo, npk ,nt                       !: size of the domain
+  INTEGER   :: nvars                                        !: Number of variables in a file
+  INTEGER   :: ntframe                                      !: Cumul of time frame
+  INTEGER , DIMENSION(:), ALLOCATABLE :: id_var , &         !: arrays of var id's
+       &                             ipk    , &         !: arrays of vertical level for each var
+       &                             id_varout,& 
+       &                             id_varout2
+  REAL(KIND=8) , DIMENSION (:,:), ALLOCATABLE :: tab, tab2  !: Arrays for cumulated values
+  REAL(KIND=8)                                :: total_time
+  REAL(KIND=4) , DIMENSION (:,:), ALLOCATABLE :: v2d ,&       !: Array to read a layer of data
+       &                                   rmean, rmean2
+  REAL(KIND=4),DIMENSION(1)                   :: timean
+  REAL(KIND=4),DIMENSION(365)                   ::  tim
+
+  CHARACTER(LEN=256) :: cfile ,cfileout, cfileout2           !: file name
+  CHARACTER(LEN=256) ::  cdep
+  CHARACTER(LEN=256) ,DIMENSION(:), ALLOCATABLE:: cvarname   !: array of var name
+  CHARACTER(LEN=256) ,DIMENSION(:), ALLOCATABLE:: cvarname2   !: array of var22 name for output
+  
+  TYPE (variable), DIMENSION(:), ALLOCATABLE :: typvar, typvar2
+
+  INTEGER    :: ncout, ncout2
+  INTEGER    :: istatus
+  LOGICAL    :: lcaltmean
+
+  !!
+
+  !!  Read command line
+  narg= iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' Usage : cdfmoy ''list_of_ioipsl_model_output_files'' '
+     STOP
+  ENDIF
+  !!
+  !! Initialisation from 1st file (all file are assume to have the same geometry)
+  CALL getarg (1, cfile)
+
+  npiglo= getdim (cfile,'x')
+  npjglo= getdim (cfile,'y')
+  npk   = getdim (cfile,'depth',cdtrue=cdep, kstatus=istatus)
+
+  IF (istatus /= 0 ) THEN
+     npk   = getdim (cfile,'z',cdtrue=cdep,kstatus=istatus)
+     IF (istatus /= 0 ) THEN
+       npk   = getdim (cfile,'sigma',cdtrue=cdep,kstatus=istatus)
+        IF ( istatus /= 0 ) THEN 
+          npk = getdim (cfile,'nav_lev',cdtrue=cdep,kstatus=istatus)
+            IF ( istatus /= 0 ) THEN 
+              npk = getdim (cfile,'levels',cdtrue=cdep,kstatus=istatus)
+              IF ( istatus /= 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( tab(npiglo,npjglo), tab2(npiglo,npjglo), v2d(npiglo,npjglo) )
+  ALLOCATE( rmean(npiglo,npjglo), rmean2(npiglo,npjglo) )
+
+  nvars = getnvar(cfile)
+  PRINT *,' nvars =', nvars
+
+  ALLOCATE (cvarname(nvars), cvarname2(nvars) )
+  ALLOCATE (typvar(nvars), typvar2(nvars) )
+  ALLOCATE (id_var(nvars),ipk(nvars),id_varout(nvars), id_varout2(nvars)  )
+
+  ! get list of variable names and collect attributes in typvar (optional)
+  cvarname(:)=getvarname(cfile,nvars,typvar)
+
+  DO jvar = 1, nvars
+     ! variables that will not be computed or stored are named 'none'
+     IF (cvarname(jvar)  /= 'vozocrtx' .AND. &
+          cvarname(jvar) /= 'vomecrty' .AND. &
+          cvarname(jvar) /= 'vovecrtz' .AND. &
+          cvarname(jvar) /= 'sossheig' ) THEN
+          cvarname2(jvar) ='none'
+     ELSE
+        cvarname2(jvar)=TRIM(cvarname(jvar))//'_sqd'
+        typvar2(jvar)%name =  TRIM(typvar(jvar)%name)//'_sqd'           ! name
+        typvar2(jvar)%units = '('//TRIM(typvar(jvar)%units)//')^2'      ! unit
+        typvar2(jvar)%missing_value = typvar(jvar)%missing_value        ! missing_value
+        typvar2(jvar)%valid_min = 0.                                    ! valid_min = zero
+        typvar2(jvar)%valid_max =  typvar(jvar)%valid_max**2            ! valid_max *valid_max
+        typvar2(jvar)%scale_factor= 1.
+        typvar2(jvar)%add_offset= 0.
+        typvar2(jvar)%savelog10= 0.
+        typvar2(jvar)%long_name =TRIM(typvar(jvar)%long_name)//'_Squared'   ! 
+        typvar2(jvar)%short_name = TRIM(typvar(jvar)%short_name)//'_sqd'     !
+        typvar2(jvar)%online_operation = TRIM(typvar(jvar)%online_operation) 
+        typvar2(jvar)%axis = TRIM(typvar(jvar)%axis) 
+
+     END IF
+  END DO
+
+  id_var(:)  = (/(jv, jv=1,nvars)/)
+  ! ipk gives the number of level or 0 if not a T[Z]YX  variable
+  ipk(:)     = getipk (cfile,nvars,cdep=cdep)
+  WHERE( ipk == 0 ) cvarname='none'
+  typvar(:)%name=cvarname
+  typvar2(:)%name=cvarname2
+
+  ! create output fileset
+  cfileout='cdfmoy.nc'
+  cfileout2='cdfmoy2.nc'
+  ! create output file taking the sizes in cfile
+
+  ncout =create(cfileout, cfile,npiglo,npjglo,npk,cdep=cdep)
+  ncout2=create(cfileout2,cfile,npiglo,npjglo,npk,cdep=cdep)
+
+  ierr= createvar(ncout , typvar,  nvars, ipk, id_varout )
+  ierr= createvar(ncout2, typvar2, nvars, ipk, id_varout2)
+
+  ierr= putheadervar(ncout , cfile, npiglo, npjglo, npk,cdep=cdep)
+  ierr= putheadervar(ncout2, cfile, npiglo, npjglo, npk,cdep=cdep)
+
+  lcaltmean=.TRUE.
+  DO jvar = 1,nvars
+     IF (cvarname(jvar) == 'nav_lon' .OR. &
+          cvarname(jvar) == 'nav_lat' ) THEN
+        ! skip these variable
+     ELSE
+        PRINT *,' Working with ', TRIM(cvarname(jvar)), ipk(jvar)
+        DO jk = 1, ipk(jvar)
+           PRINT *,'level ',jk
+           tab(:,:) = 0.d0 ; tab2(:,:) = 0.d0 ; total_time = 0.;  ntframe=0
+           DO jt = 1, narg
+              CALL getarg (jt, cfile)
+              nt = getdim (cfile,'time_counter')
+              IF ( lcaltmean )  THEN
+                 tim=getvar1d(cfile,'time_counter',nt)
+                 total_time = total_time + SUM(tim(1:nt) )
+              END IF
+              DO jtt=1,nt
+                ntframe=ntframe+1
+                jkk=jk
+                ! If forcing fields is without depth dimension
+                IF (npk==0) jkk=jtt 
+                v2d(:,:)= getvar(cfile, cvarname(jvar), jkk ,npiglo, npjglo,ktime=jtt )
+                tab(:,:) = tab(:,:) + v2d(:,:)
+                IF (cvarname2(jvar) /= 'none' ) tab2(:,:) = tab2(:,:) + v2d(:,:)*v2d(:,:)
+              ENDDO
+           END DO
+           ! finish with level jk ; compute mean (assume spval is 0 )
+           rmean(:,:) = tab(:,:)/ntframe
+           IF (cvarname2(jvar) /= 'none' ) rmean2(:,:) = tab2(:,:)/ntframe
+           ! store variable on outputfile
+           ierr = putvar(ncout, id_varout(jvar) ,rmean, jk, npiglo, npjglo, kwght=ntframe)
+           IF (cvarname2(jvar) /= 'none' ) ierr = putvar(ncout2,id_varout2(jvar),rmean2, jk,npiglo, npjglo, kwght=ntframe)
+           IF (lcaltmean )  THEN
+              timean(1)= total_time/ntframe
+              ierr=putvar1d(ncout,timean,1,'T')
+              ierr=putvar1d(ncout2,timean,1,'T')
+           END IF
+           lcaltmean=.FALSE. ! tmean already computed
+        END DO  ! loop to next level
+     END IF
+  END DO ! loop to next var in file
+
+  istatus = closeout(ncout)
+  istatus = closeout(ncout2)
+
+
+END PROGRAM cdfmoy

+ 205 - 0
cdftools_light/src/cdfmxl.f90

@@ -0,0 +1,205 @@
+PROGRAM cdfmxl
+  !!---------------------------------------------------------------------
+  !!               ***  PROGRAM cdfmxl  ***
+  !!
+  !!  **  Purpose: Compute mixed layer depth 
+  !!  
+  !!  **  Method: Try to avoid 3 d arrays.
+  !!            - compute surface properties
+  !!            - initialize depths and model levels number
+  !!            - from bottom to top compute rho and
+  !!              check if rho > rho_surf +rho_c
+  !!              where rho_c is a density criteria given as argument
+  !!
+  !! history :
+  !!   Original :  J.M. Molines (October 2005)
+  !!---------------------------------------------------------------------
+  !!  $Rev: 256 $
+  !!  $Date: 2009-07-21 17:49:27 +0200 (Tue, 21 Jul 2009) $
+  !!  $Id: cdfmxl.f90 256 2009-07-21 15:49:27Z molines $
+  !!--------------------------------------------------------------
+  !! * Modules used
+  USE cdfio
+  USE eos
+
+  !! * Local variables
+  IMPLICIT NONE
+  INTEGER :: ji,jj,jk, jt, ik1, ik2, ikt  !LB
+  INTEGER :: narg, iargc, istatus !LB
+  INTEGER :: npiglo, npjglo, npk, nt !LB
+  INTEGER ,  DIMENSION(:,:), ALLOCATABLE :: mbathy       !: number of w levels in water <= npk
+  INTEGER ,  DIMENSION(:,:), ALLOCATABLE :: nmln1  ,&    !: last level where rho > rho + rho_c1
+      &                                     nmln2  ,&    !: last level where rho > rho + rho_c2
+      &                                     nmlnt        !: last level where temp > temp +temp_c  (temp_c<0)
+
+  REAL(KIND=4) :: rho_c1=0.01, rho_c2=0.03,  temp_c=-0.2
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE :: temp, &   !: temperatures
+      &                                        sal,  &   !: salinity
+      &                                        rho,  &   !: current density
+      &                                    rho_surf, &   !: surface density
+      &                                    tem_surf, &   !: surface temperature
+      &                                    hmlp1   , &   !: mixed layer depth based on density criterium 1
+      &                                    hmlp2   , &   !: mixed layer depth based on density criterium 2
+      &                                    hmlt    , &   !: mixed layer depth based on Temp Criterium
+      &                              zmask_surf    , &   !: mixed layer depth
+      &                                    zmask         !: tmask at current level
+  REAL(KIND=4), DIMENSION(:), ALLOCATABLE   :: gdepw     !: depth of w levels
+
+  CHARACTER(LEN=256) :: cfilet,  ctim, coordzgr='mesh_zgr.nc'  !LB
+  CHARACTER(LEN=256) :: cbathy='bathy_level.nc'
+
+  ! output stuff
+  INTEGER                         :: ncout, ierr
+  INTEGER,           DIMENSION(3) :: ipk, id_varout  !: only one output variable
+  REAL(KIND=4),      DIMENSION(1) :: tim,dep       !: time output
+  CHARACTER(LEN=256)               :: cfileout='mxl.nc'
+
+  TYPE(variable), DIMENSION(3)    :: typvar        !: structure for attributes
+
+  LOGICAL  :: lexist                               !: flag for existence of bathy_level file
+
+  !! 0- Get started ..
+  !!
+  !  Read command line and output usage message if not compliant.
+  narg= iargc()
+  IF ( narg < 1  ) THEN
+     PRINT *,' Usage : cdfmxl gridTfile '
+     PRINT *,' Files  mesh_zgr.nc must be in the current directory ^**'
+     PRINT *,' Output on mxl.nc '
+     PRINT *,'          variable somxl010 = mld on density criterium 0.01'
+     PRINT *,'          variable somxl030 = mld on density criterium 0.03'
+     PRINT *,'          variable somxlt02 = mld on temperature criterium -0.2'
+     PRINT *,'  ^** : In case of FULL STEP run, bathy_level.nc must also be in the directory'
+     STOP
+  ENDIF
+  CALL getarg (1, cfilet)
+
+  ! read dimensions 
+  npiglo= getdim (cfilet,'x')
+  npjglo= getdim (cfilet,'y')
+  npk   = getdim (cfilet,'depth')
+  ctim='none'
+  nt     = getdim(cfilet,'time', cdtrue=ctim,kstatus=istatus) !LB
+
+
+  dep(1) = 0.
+  ipk(:)= npk  ! all variables ( output are 2D)
+
+  typvar(1)%name= 'somxl010'
+  typvar(2)%name= 'somxl030'
+  typvar(3)%name= 'somxlt02'
+  typvar%units='m'
+  typvar%missing_value=0.
+  typvar%valid_min= 0.
+  typvar%valid_max= 7000.
+  typvar(1)%long_name='Mixed_Layer_Depth_on_0.01_rho_crit'
+  typvar(2)%long_name='Mixed_Layer_Depth_on_0.03_rho_crit'
+  typvar(3)%long_name='Mixed_Layer_Depth_on_-0.2_temp_crit'
+  typvar(1)%short_name='somxl010'
+  typvar(2)%short_name='somxl030'
+  typvar(3)%short_name='somxlt02'
+  typvar%online_operation='N/A'
+  typvar%axis='TYX'
+
+
+  PRINT *, 'npiglo=', npiglo
+  PRINT *, 'npjglo=', npjglo
+  PRINT *, 'npk   =', npk
+
+  ALLOCATE (temp(npiglo,npjglo), sal(npiglo,npjglo), rho(npiglo,npjglo))
+  ALLOCATE (rho_surf(npiglo,npjglo) ,tem_surf(npiglo,npjglo))
+  ALLOCATE (zmask(npiglo,npjglo),zmask_surf(npiglo,npjglo)    )
+  ALLOCATE (hmlp1(npiglo,npjglo),hmlp2(npiglo,npjglo), hmlt(npiglo,npjglo) )
+  ALLOCATE (mbathy(npiglo,npjglo) )
+  ALLOCATE (nmln1(npiglo,npjglo), nmln2(npiglo,npjglo),nmlnt(npiglo,npjglo) )
+  ALLOCATE ( gdepw(npk) )
+  
+  ! read mbathy and gdepw use real temp(:,:) as template (getvar is used for real only)
+  INQUIRE (FILE=cbathy, EXIST=lexist)
+  IF ( lexist ) THEN
+    temp(:,:) = getvar(cbathy,'Bathy_level',1, npiglo, npjglo)
+  ELSE
+    temp(:,:) = getvar(coordzgr,'mbathy',1, npiglo, npjglo)
+  ENDIF
+  mbathy(:,:) = temp(:,:)
+  gdepw(:) = getvare3(coordzgr, 'gdepw',npk)
+
+
+
+
+
+  DO jt = 1, nt !LB
+
+     PRINT *, ' * [cdfmxl] jt = ', jt
+
+     !! 1- Get surface properties
+     !!
+     ! read surface T and S and deduce land-mask from salinity
+     temp(:,:) = getvar(cfilet, 'votemper',  1 ,npiglo,npjglo, ktime=jt) !LB
+     sal (:,:) = getvar(cfilet, 'vosaline',  1 ,npiglo,npjglo, ktime=jt) !LB
+     zmask(:,:) = 1.; WHERE ( sal == 0. ) zmask = 0.
+     zmask_surf(:,:) = zmask(:,:)
+     
+     ! compute rho_surf
+     rho_surf(:,:) = sigma0 ( temp,sal,npiglo,npjglo )* zmask(:,:)
+     tem_surf(:,:) = temp(:,:)
+     
+     ! Initialization to the number of w ocean point mbathy
+     nmln1(:,:) = mbathy(:,:)
+     nmln2(:,:) = mbathy(:,:)
+     nmlnt(:,:) = mbathy(:,:)
+     
+     !! 2- determine mixed layer
+     !!
+     ! Last w-level at which rhop>=rho surf+rho_c (starting from jpk-1)
+     ! (rhop defined at t-point, thus jk-1 for w-level just above)
+     DO jk = npk-1, 2, -1
+        temp(:,:) = getvar(cfilet, 'votemper',  jk ,npiglo,npjglo, ktime=jt)
+        sal (:,:) = getvar(cfilet, 'vosaline',  jk ,npiglo,npjglo, ktime=jt)
+        zmask(:,:) = 1.  ; WHERE ( sal == 0. ) zmask = 0.
+        rho(:,:)  = sigma0 ( temp,sal,npiglo,npjglo )* zmask(:,:)
+        
+        DO jj = 1, npjglo
+           DO ji = 1, npiglo
+              IF( rho(ji,jj)  > rho_surf(ji,jj) + rho_c1 )   nmln1(ji,jj) = jk
+              IF( rho(ji,jj)  > rho_surf(ji,jj) + rho_c2 )   nmln2(ji,jj) = jk
+              IF( ABS(temp(ji,jj) - tem_surf(ji,jj)) > ABS( temp_c)  )   nmlnt(ji,jj) = jk
+           END DO
+        END DO
+     END DO
+     
+     ! Mixed layer depth
+     DO jj = 1, npjglo
+        DO ji = 1, npiglo
+           ik1 = nmln1(ji,jj) ; ik2 = nmln2(ji,jj) ; ikt = nmlnt(ji,jj)
+           hmlp1 (ji,jj) = gdepw(ik1) * zmask_surf(ji,jj)
+           hmlp2 (ji,jj) = gdepw(ik2) * zmask_surf(ji,jj)
+           hmlt (ji,jj)  = gdepw(ikt) * zmask_surf(ji,jj)
+        END DO
+     END DO
+
+
+     !! 3- Write output file
+     !!
+
+     !LB:
+     IF ( jt == 1) THEN
+        ncout = create(cfileout, cfilet, npiglo,npjglo,1)
+        ierr = createvar(ncout ,typvar ,3, ipk, id_varout )
+        ierr= putheadervar(ncout, cfilet,npiglo, npjglo,1,pdep=dep)        
+        tim = getvar1d(cfilet,'time_counter', nt)
+        ierr= putvar1d(ncout, tim, nt, 'T')
+     END IF
+     !LB.
+     
+     ierr = putvar(ncout, id_varout(1) ,hmlp1, 1, npiglo, npjglo, jt) !LB
+     ierr = putvar(ncout, id_varout(2) ,hmlp2, 1, npiglo, npjglo, jt) !LB
+     ierr = putvar(ncout, id_varout(3) ,hmlt , 1, npiglo, npjglo, jt) !LB
+
+
+  END DO  !LB jt
+  
+  ierr=closeout(ncout)
+  
+
+END PROGRAM cdfmxl

+ 192 - 0
cdftools_light/src/cdfpsi.f90

@@ -0,0 +1,192 @@
+PROGRAM cdfpsi
+   !!-------------------------------------------------------------------
+   !!               ***  PROGRAM cdfpsi  ***
+   !!
+   !!  **  Purpose  :  Compute Barotropic Stream Function
+   !!                  PARTIAL STEPS
+   !!
+   !!  **  Method   :  Compute the 2D fields ztrpu, ztrpv
+   !!                  as the integral on the vertical of u, v on their
+   !!                  respective points.
+   !!                  Then integrate from West to East   : ==> psiv
+   !!                  (should be almost the same (if no error ))
+   !!   Default (appropriate for global model): output psiu;
+   !!                    normalizes the values setting psi (jpi,jpj) = 0
+   !!   If option "V" is given as last argument, output psiv,
+   !!                    normalizes values setting psi(jpi,1) = 0.
+   !!                    This is appropriate for North Atlantic
+   !!
+   !! history ;
+   !!  Original :  J.M. Molines (May 2005 )
+   !!-------------------------------------------------------------------
+   !!  $Rev: 256 $
+   !!  $Date: 2009-07-21 17:49:27 +0200 (Tue, 21 Jul 2009) $
+   !!  $Id: cdfpsi.f90 256 2009-07-21 15:49:27Z molines $
+   !!--------------------------------------------------------------
+   !! * Modules used
+   USE cdfio
+   USE io_ezcdf
+
+   IMPLICIT NONE
+
+   !INTEGER, PARAMETER :: nb_basins = 3
+   !CHARACTER(len=3), DIMENSION(3), PARAMETER :: cb_lab = (/ 'atl','pac','ind' /)
+   !CHARACTER(len=8), DIMENSION(3), PARAMETER :: cb_lgn = (/ 'Atlantic','Pacific ','Indian  ' /)
+   INTEGER, PARAMETER :: nb_basins = 2
+   CHARACTER(len=3), DIMENSION(nb_basins), PARAMETER :: cb_lab = (/ 'atl','pac' /)
+   CHARACTER(len=8), DIMENSION(nb_basins), PARAMETER :: cb_lgn = (/ 'Atlantic','Pacific ' /)
+
+   INTEGER   :: ji,jj,jk,jt                         !: dummy loop index
+   INTEGER   :: ierr                                !: working integer
+   INTEGER   :: narg, iargc                         !: command line
+   INTEGER   :: npiglo,npjglo, npk, nt              !: size of the domain
+   INTEGER   :: ncout
+   INTEGER, DIMENSION(nb_basins) ::  ipk, id_varout         !
+   TYPE(variable), DIMENSION(nb_basins)  :: typvar         !: structure for attributes
+
+   REAL(KIND=4), DIMENSION (:,:),   ALLOCATABLE ::  zmask, e1v, e2u, glamf, gphif
+   REAL(KIND=4), DIMENSION (:,:,:),   ALLOCATABLE ::  zmask_basin
+   REAL(KIND=4) ,DIMENSION(:),      ALLOCATABLE ::  tim
+
+   REAL(4), DIMENSION(:,:,:), ALLOCATABLE :: E3V_3D, V_3D
+
+
+   REAL(KIND=8),   DIMENSION (:,:), ALLOCATABLE ::  ztrpv, psiv
+
+   CHARACTER(LEN=256) :: cfileu ,cfilev, cfileoutnc='psi.nc', ctim
+   CHARACTER(LEN=256) :: cf_mm='mesh_mask.nc'
+   CHARACTER(LEN=256) :: cf_bm='new_maskglo.nc'
+   CHARACTER(LEN=1)  :: coption
+
+
+   CHARACTER(LEN=64) :: cv_u, cv_v
+
+   INTEGER    :: istatus, jb
+
+   INTEGER :: idf_0=0, idv_0=0,        &
+      &    idf_u=0, idv_u=0, idf_v=0, idv_v=0
+
+   ! constants
+
+   !!  Read command line and output usage message if not compliant.
+   narg= iargc()
+   IF ( narg == 0 ) THEN
+      PRINT *,' Usage : cdfpsi  Ufile Vfile nameU nameV (optional argument)'
+      PRINT *,' Computes the barotropic stream function as the integral of the transport'
+      PRINT *,' PARTIAL CELLS VERSION'
+      PRINT *,' Files mesh_mask.nc and new_maskglo.nc must be in te current directory'
+      PRINT *,' Output on psi.nc, variables sobarstf on f-points'
+      PRINT *,' Default works well for a global ORCA grid. use V 3rdargument for North Atlantic'
+      STOP
+   ENDIF
+
+   CALL getarg (1, cfileu  )
+   CALL getarg (2, cfilev  )
+   CALL getarg (3, cv_u)
+   CALL getarg (4, cv_v)
+
+   npiglo= getdim (cfileu,'x')
+   npjglo= getdim (cfileu,'y')
+   npk   = getdim (cfileu,'depth')
+
+   ctim = 'none'
+   nt    = getdim (cfileu,'time',cdtrue=ctim,kstatus=istatus) !LB
+
+   !lolo
+   DO jb = 1, nb_basins
+      ! define new variables for output ( must update att.txt)
+      typvar(jb)%name='psi_'//TRIM(cb_lab(jb))
+      typvar(jb)%units='10^6 m^3/s'
+      typvar(jb)%missing_value=-9999.
+      typvar(jb)%valid_min= -300.e6
+      typvar(jb)%valid_max= 300.e6
+      typvar(jb)%long_name='Barotropic_Stream_Function_'//TRIM(cb_lgn(jb))
+      typvar(jb)%short_name='psi_'//TRIM(cb_lab(jb))
+      typvar(jb)%online_operation='N/A'
+      typvar(jb)%axis='TYX'
+      ipk(jb) = 1  !  2D ( X, Y , T )
+   END DO
+
+
+   PRINT *, 'npiglo=', npiglo
+   PRINT *, 'npjglo=', npjglo
+   PRINT *, 'npk   =', npk
+   PRINT *, 'nt   =', nt !LB
+
+
+   ! Allocate arrays
+   ALLOCATE ( zmask(npiglo,npjglo), zmask_basin(npiglo,npjglo,nb_basins) )
+   ALLOCATE ( e1v(npiglo,npjglo), e2u(npiglo,npjglo), E3V_3D(npiglo,npjglo,npk))
+   ALLOCATE ( V_3D(npiglo,npjglo,npk) )
+   ALLOCATE ( ztrpv(npiglo,npjglo), psiv(npiglo,npjglo))
+   ALLOCATE ( glamf(npiglo,npjglo), gphif(npiglo,npjglo))
+   ALLOCATE ( tim(nt) ) !LB
+
+   glamf(:,:) = getvar(cf_mm, 'glamf',1,npiglo,npjglo)
+   gphif(:,:) = getvar(cf_mm, 'gphif',1,npiglo,npjglo)
+
+   ! create output fileset
+   ncout =create(cfileoutnc, cfileu, npiglo,npjglo,1)
+   ierr= createvar(ncout ,typvar,nb_basins, ipk,id_varout )
+   ierr= putheadervar(ncout, cfileu,npiglo, npjglo,1,glamf, gphif)
+   tim=getvar1d(cfileu,trim(ctim),nt) !LB
+   ierr=putvar1d(ncout,tim,nt,'T') !LB
+
+
+   e1v(:,:)   = getvar(cf_mm, 'e1v', 1,npiglo,npjglo)
+   e2u(:,:)   = getvar(cf_mm, 'e2u', 1,npiglo,npjglo)
+   zmask(:,:) = getvar(cf_mm, 'fmask', 1,npiglo,npjglo)
+
+
+
+   ! get e3u, e3v  at all levels
+   CALL GETVAR_3D(idf_0, idv_0, cf_mm, 'e3v_0', 0, 0, E3V_3D) ; idf_0 = 0. ; idv_0 = 0.
+
+   ! get rid of the free-slip/no-slip condition
+   WHERE ( zmask >= 2 ) zmask = 1
+
+
+
+   DO jt=1,nt
+
+      PRINT *, ' * [cdfpsi] jt = ', jt
+
+      CALL GETVAR_3D(idf_v, idv_v, cfilev, cv_v, nt, jt, V_3D)
+
+      !! Loop over basins:
+      DO jb = 1, nb_basins
+         
+         PRINT *, ''
+         
+         IF ( jt == 1 ) THEN
+            PRINT *, ' Getting mask for basin ', TRIM(cb_lgn(jb)),' => ', TRIM(cb_lab(jb))
+            zmask_basin(:,:,jb) = getvar(cf_bm, 'tmask'//TRIM(cb_lab(jb)), 1,npiglo,npjglo) * zmask(:,:)
+         END IF
+         
+         ztrpv(:,:)= 0.d0
+         !psiv(npiglo,:)= 0.d0
+         psiv(:,:) = 0.d0
+
+         DO jk = 1,npk
+            ztrpv(:,:) = ztrpv(:,:) + V_3D(:,:,jk)*e1v(:,:)*E3V_3D(:,:,jk)  ! meridional transport of each grid cell
+         END DO  ! loop to next level
+
+
+         ! integrate zonally from east to west            
+         DO ji = npiglo-1, 1, -1
+            psiv(ji,:) = psiv(ji+1,:) - ztrpv(ji,:)  ! psi at f point
+         END DO
+         psiv(:,:) = 1.E-6 * psiv(:,:)*zmask_basin(:,:,jb)
+         WHERE ( zmask_basin(:,:,jb) == 0. ) psiv(:,:) = -9999.
+         WHERE ( psiv(:,:) < -10000. ) psiv(:,:) = 0.
+            
+         ierr = putvar(ncout, id_varout(jb), SNGL(psiv), 1, npiglo, npjglo, jt) !LB
+            
+      END DO  ! DO jb = 1, nb_basins
+
+   END DO  ! DO jt=1,nt
+   
+
+   istatus = closeout (ncout)
+
+END PROGRAM cdfpsi

+ 92 - 0
cdftools_light/src/cdfrmsssh.f90

@@ -0,0 +1,92 @@
+PROGRAM cdfrmsssh
+  !!-------------------------------------------------------------------
+  !!             ***  PROGRAM cdfrmsssh  ***
+  !!
+  !!  **  Purpose: Compute RMS SSH
+  !!  
+  !!  **  Method: Try to avoid 3 d arrays 
+  !!
+  !! history :
+  !!  Original :  J.M. Molines (Nov 2004 ) for ORCA025
+  !!              J.M. Molines Apr 2005 : use modules
+  !!-------------------------------------------------------------------
+  !!  $Rev: 256 $
+  !!  $Date: 2009-07-21 17:49:27 +0200 (Tue, 21 Jul 2009) $
+  !!  $Id: cdfrmsssh.f90 256 2009-07-21 15:49:27Z molines $
+  !!--------------------------------------------------------------
+  !! * Modules used
+  USE cdfio
+
+  !! * Local variables
+  IMPLICIT NONE
+  INTEGER   :: ji,jj,jk
+  INTEGER   :: narg, iargc                          !: 
+  INTEGER   :: npiglo,npjglo, npk                   !: size of the domain
+  INTEGER, DIMENSION(1) ::  ipk, id_varout
+  REAL(KIND=4) , DIMENSION (:,:), ALLOCATABLE :: u, u2,  rms
+  REAL(KIND=4) ,DIMENSION(1)                  :: timean
+
+  CHARACTER(LEN=256) :: cfile ,cfile2 ,cfileout='rms.nc'            !: file name
+
+  TYPE(variable), DIMENSION(1) :: typvar          !: structure for attribute
+
+  INTEGER    :: ncout
+  INTEGER    :: istatus, ierr
+
+  !!  Read command line
+  narg= iargc()
+  IF ( narg /= 2 ) THEN
+     PRINT *,' Usage : cdfrmsssh ''gridX gridX2'' '
+     PRINT *,'   Output on rms.nc , variable sossheig_rms '
+     STOP
+  ENDIF
+  !!
+  !! Initialisation from 1st file (all file are assume to have the same geometry)
+  CALL getarg (1, cfile)
+  CALL getarg (2, cfile2)
+
+  npiglo= getdim (cfile,'x')
+  npjglo= getdim (cfile,'y')
+  npk   = getdim (cfile,'depth')
+
+  ipk(1) = 1
+  typvar(1)%name= 'sossheig_rms'
+  typvar(1)%units='m'
+  typvar(1)%missing_value=0.
+  typvar(1)%valid_min= 0.
+  typvar(1)%valid_max= 100.
+  typvar(1)%long_name='RMS_Sea_Surface_height'
+  typvar(1)%short_name='sossheig_rms'
+  typvar(1)%online_operation='N/A'
+  typvar(1)%axis='TYX'
+
+
+  PRINT *, 'npiglo=', npiglo
+  PRINT *, 'npjglo=', npjglo
+  PRINT *, 'npk   =', npk
+
+  ALLOCATE( u(npiglo,npjglo), u2(npiglo,npjglo) )
+  ALLOCATE( rms(npiglo,npjglo) )
+
+  ncout =create(cfileout, cfile,npiglo,npjglo,npk)
+
+  ierr= createvar(ncout ,typvar,1, ipk,id_varout )
+  ierr= putheadervar(ncout, cfile, npiglo, npjglo, npk)
+
+  DO jk = 1, ipk(1)
+     u(:,:) = getvar(cfile,'sossheig',jk, npiglo, npjglo)
+     u2(:,:) = getvar(cfile2,'sossheig_sqd',jk, npiglo, npjglo)
+
+     rms(:,:) = 0.
+     DO ji=2, npiglo
+        DO jj=2,npjglo
+           rms(ji,jj)  =  SQRT((u2(ji,jj)-u(ji,jj)*u(ji,jj)))
+        END DO
+     END DO
+     ierr=putvar(ncout,id_varout(1), rms, jk, npiglo, npjglo)
+  END DO
+  timean=getvar1d(cfile,'time_counter',1)
+  ierr=putvar1d(ncout,timean,1,'T')
+  istatus = closeout(ncout)
+
+END PROGRAM cdfrmsssh

+ 646 - 0
cdftools_light/src/cdfsigtrp.f90

@@ -0,0 +1,646 @@
+PROGRAM cdfsigtrp
+
+  !!---------------------------------------------------------------------
+  !!               ***  PROGRAM cdfsigtrp  ***
+  !!
+  !!  **  Purpose: Compute density class Mass Transports  across a section
+  !!               PARTIAL STEPS version
+  !!
+  !!  **  Method:
+  !!        -The beginner and end point of the section are given in term of f-points index.
+  !!        -The progracdfm 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 uo or vo )
+  !!            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 :
+  !!   Original :  J.M. Molines March 2006
+  !!            :  R. Dussin (Jul. 2009) add cdf output
+  !!---------------------------------------------------------------------
+  !!  $Rev: 322 $
+  !!  $Date: 2010-05-20 07:14:33 +0200 (Thu, 20 May 2010) $
+  !!  $Id: cdfsigtrp.f90 322 2010-05-20 05:14:33Z molines $
+  !!--------------------------------------------------------------
+  !! * Modules used
+  USE netcdf
+  USE cdfio
+  USE io_ezcdf
+  USE eos
+
+  !! * Local variables
+  IMPLICIT NONE
+  INTEGER   :: nbins                                  !: number of density classes
+  INTEGER   :: ji, jk, jt, jclass, jsec,jiso , jbin,jarg  !: dummy loop index
+  INTEGER   :: narg, iargc                            !: command line
+  INTEGER   :: npiglo,npjglo, npk, nk, nt                                !: vertical size, number of wet layers in the section
+
+  INTEGER                            :: nsection                    !: number of sections (overall)
+  INTEGER ,DIMENSION(:), ALLOCATABLE :: imina, imaxa, jmina, jmaxa  !: sections limits
+  INTEGER                            :: imin, imax, jmin, jmax      !: working section limits
+  INTEGER                            :: npts                        !: working section number of h-points
+  ! added to write in netcdf
+  INTEGER :: kx=1, ky=1                ! dims of netcdf output file
+  INTEGER :: nboutput=2                ! number of values to write in cdf output
+  INTEGER :: ierr, istatus      ! for netcdf output
+  INTEGER, DIMENSION(:), ALLOCATABLE ::  ipk, id_varout
+
+  REAL(KIND=4), DIMENSION (:),     ALLOCATABLE :: gdept, gdepw !: depth of T and W points
+  REAL(KIND=4), DIMENSION (:,:),   ALLOCATABLE :: zs, zt       !: salinity and temperature from file
+  REAL(KIND=4), DIMENSION (:,:,:), ALLOCATABLE :: XOUT, tmpm, tmpz   !: temporary arrays
+
+  ! double precision for cumulative variables and densities
+  REAL(KIND=8), DIMENSION (:),     ALLOCATABLE ::  eu                 !: either e1v or e2u
+  REAL(KIND=8), DIMENSION (:,:),   ALLOCATABLE ::  zu, e3 , zmask     !: velocities e3 and umask
+  REAL(KIND=8), DIMENSION (:,:),   ALLOCATABLE ::  zsig ,gdepu        !: density, depth of vel points
+  REAL(KIND=8)                                 :: sigma_min, sigma_max,dsigma   !: Min and Max for sigma bining
+  REAL(KIND=8)                                 :: sigma,zalfa                   !: current working sigma
+  REAL(KIND=8), DIMENSION (:),   ALLOCATABLE   :: sigma_lev, sigma_lev_center   !: built array with sigma levels
+  REAL(KIND=8), DIMENSION (:,:), ALLOCATABLE   :: hiso                          !: depth of isopycns
+
+  REAL(KIND=8), DIMENSION (:,:), ALLOCATABLE   :: zwtrp, zwtrpbin       !: transport arrays
+  ! added to write in netcdf
+  REAL(KIND=4), DIMENSION(:,:), ALLOCATABLE ::  dumlon, dumlat
+
+  REAL(KIND=4) ,DIMENSION(:), ALLOCATABLE  ::  tim !LB
+
+  TYPE(variable), DIMENSION(:), ALLOCATABLE :: typvar  ! structure of output
+  TYPE(variable), DIMENSION(:), ALLOCATABLE :: typvarin  !: structure for recovering input informations such as iwght
+  CHARACTER(LEN=256), DIMENSION(:),ALLOCATABLE :: cvarname !: names of input variables
+  INTEGER                                   :: nvarin    !: number of variables in input file
+  INTEGER                                   :: iweight   !: weight of input file for further averaging
+
+  CHARACTER(LEN=256) :: cd_out = '.', cf_out
+  REAL :: ryear
+
+  CHARACTER(LEN=256), DIMENSION (:), ALLOCATABLE :: csection                     !: section name
+  CHARACTER(LEN=256) :: cfilet, cfileu, cfilev, cfilesec='dens_section.dat'      !: files name
+  CHARACTER(LEN=256) :: cf_mm='mesh_mask.nc'                                     !: coordinates files
+  CHARACTER(LEN=256) :: cdum
+  ! added to write in netcdf
+  CHARACTER(LEN=256) :: ctim
+
+  LOGICAL    :: l_merid                     !: flag is true for meridional working section
+  LOGICAL    :: lfncout = .false.
+
+  CHARACTER(LEN=80) :: cfor9000, cfor9001, cfor9002, cfor9003, cfor9004
+
+
+  REAL(4), DIMENSION(:,:),   ALLOCATABLE :: E2U_2D, E1V_2D
+  REAL(4), DIMENSION(:,:,:), ALLOCATABLE :: T_3D, S_3D, U_3D, V_3D, E3U_3D, E3V_3D, E3W_3D
+
+  INTEGER, DIMENSION(:), ALLOCATABLE :: id_var_out
+  
+  CHARACTER(LEN=64) :: cv_t, cv_s, cv_u, cv_v
+ 
+  INTEGER :: jt_pos, idf_out, idd_t, idd_sbins, idv_time, idv_sbins
+
+  INTEGER :: idf_0=0, idv_0=0, idf_t=0, idv_t=0, idf_s=0, idv_s=0, idf_u=0, &
+     &       idv_u=0, idf_v=0, idv_v=0
+
+
+
+
+
+
+
+
+
+
+  !!  * Initialisations
+
+  !  Read command line and output usage message if not compliant.
+  narg= iargc()
+  IF ( narg < 12  ) THEN
+     PRINT *, ''
+     PRINT *,' Usage: cdfsigtrp.x <Tfile> <Ufile> <Vfile> s_min s_max nbins <year> <DIROUT> <name T> <name S> <name U> <name V>'
+     PRINT *,'         *   s_min, s_max : limit for density bining '
+     PRINT *,'         *   nbins        : number of bins to use '
+     PRINT *, ''
+     PRINT *,' File mesh_mask.nc must be in the current directory'
+     PRINT *,' File dens_section.dat must also be in the current directory '
+     STOP
+  ENDIF
+
+  !! Read arguments
+  CALL getarg (1, cfilet)
+  CALL getarg (2, cfileu)
+  CALL getarg (3, cfilev)
+  CALL getarg (4,cdum)           ; READ(cdum,*) sigma_min
+  CALL getarg (5,cdum)           ; READ(cdum,*) sigma_max
+  CALL getarg (6,cdum)           ; READ(cdum,*) nbins
+  CALL getarg (7, cdum)          ; READ(cdum,*) ryear
+  CALL getarg (8, cd_out)
+  CALL getarg (9,  cv_t)
+  CALL getarg (10, cv_s)
+  CALL getarg (11, cv_u)
+  CALL getarg (12, cv_v)
+
+
+  ! start for netcdf:
+  nvarin=getnvar(cfileu)  ! smaller than cfilet
+  ALLOCATE(typvarin(nvarin), cvarname(nvarin)  )
+  cvarname(:)=getvarname(cfileu,nvarin,typvarin)
+
+  DO  jarg=1,nvarin
+     IF ( TRIM(cvarname(jarg))  == trim(cv_u) ) THEN
+        iweight=typvarin(jarg)%iwght
+        EXIT  ! loop
+     ENDIF
+  END DO
+
+
+  ALLOCATE ( typvar(nboutput), ipk(nboutput), id_varout(nboutput) )
+  ALLOCATE (dumlon(kx,ky) , dumlat(kx,ky) )
+
+  dumlon(:,:)=0.
+  dumlat(:,:)=0.
+
+  ipk(1)=nbins ! sigma for each level
+  ipk(2)=nbins ! transport for each level
+
+  ! define new variables for output
+  typvar(1)%name='sigma_class'
+  typvar%units='[]'
+  typvar%missing_value=99999.
+  typvar%valid_min= 0.
+  typvar%valid_max= 100.
+  typvar%scale_factor= 1.
+  typvar%add_offset= 0.
+  typvar%savelog10= 0.
+  typvar%iwght=iweight
+  typvar(1)%long_name='class of potential density'
+  typvar(1)%short_name='sigma_class'
+  typvar%online_operation='N/A'
+  typvar%axis='ZT'
+
+  typvar(2)%name='sigtrp'
+  typvar(2)%units='Sv'
+  typvar(2)%valid_min= -1000.
+  typvar(2)%valid_max= 1000.
+  typvar(2)%long_name='transport in sigma class'
+  typvar(2)%short_name='sigtrp'
+
+  !end of netcdf...
+
+
+
+  INQUIRE( FILE=cfilesec, EXIST=lfncout )
+  IF ( .NOT. lfncout ) THEN
+     PRINT *, 'ERROR: file '//trim(cfilesec)//' not found!' ; STOP
+  END IF
+
+
+
+
+  ! Initialise sections from file
+  ! first call to get nsection and allocate arrays
+  nsection = 0 ; CALL section_init(cfilesec, csection,imina,imaxa,jmina,jmaxa, nsection)
+  ALLOCATE ( csection(nsection), imina(nsection), imaxa(nsection), jmina(nsection),jmaxa(nsection) )
+  CALL section_init(cfilesec, csection,imina,imaxa,jmina,jmaxa, nsection)
+
+
+  ! Allocate and build sigma levels and section array
+  ALLOCATE ( sigma_lev(nbins+1), sigma_lev_center(nbins) )
+
+  sigma_lev(1)=sigma_min
+  dsigma=( sigma_max - sigma_min) / nbins
+  DO jclass =2, nbins+1
+     sigma_lev(jclass)= sigma_lev(1) + (jclass-1) * dsigma
+  END DO
+
+  DO jclass =1, nbins
+     sigma_lev_center(jclass) = 0.5*(sigma_lev(jclass) + sigma_lev(jclass+1))
+  END DO
+
+  ctim = 'none'
+  nt    = getdim (cfilet,'time',cdtrue=ctim,kstatus=istatus) !LB
+
+
+  ALLOCATE ( tim(nt), XOUT(nsection, nbins, nt), id_var_out(nsection) ) !LB
+
+
+
+  ! Look for vertical size of the domain
+  npiglo= getdim (cfilet,'x')
+  npjglo= getdim (cfilet,'y')
+  npk   = getdim (cfilet,'depth')
+
+  ALLOCATE ( gdept(npk), gdepw(npk) )
+
+
+  ALLOCATE ( T_3D(npiglo,npjglo,npk), S_3D(npiglo,npjglo,npk), &
+       &     U_3D(npiglo,npjglo,npk), V_3D(npiglo,npjglo,npk), &
+       &     E2U_2D(npiglo,npjglo), E1V_2D(npiglo,npjglo),     &
+       &     E3U_3D(npiglo,npjglo,npk), E3V_3D(npiglo,npjglo,npk), E3W_3D(npiglo,npjglo,npk) )
+
+
+
+  ! read gdept, gdepw : it is OK even in partial cells, as we never use the bottom gdep
+  gdept(:) = getvare3(cf_mm,'gdept', npk)
+  gdepw(:) = getvare3(cf_mm,'gdepw', npk)
+
+
+
+
+
+  !lolo
+  ! get e3u, e3v  at all levels
+  CALL GETVAR_2D(idf_0, idv_0, cf_mm, 'e2u',   0, 0, 0, E2U_2D) ; idf_0 = 0 ; idv_0 = 0
+  CALL GETVAR_2D(idf_0, idv_0, cf_mm, 'e1v',   0, 0, 0, E1V_2D) ; idf_0 = 0 ; idv_0 = 0
+  CALL GETVAR_3D(idf_0, idv_0, cf_mm, 'e3u_0', 0, 0, E3U_3D) ; idf_0 = 0 ; idv_0 = 0
+  CALL GETVAR_3D(idf_0, idv_0, cf_mm, 'e3v_0', 0, 0, E3V_3D) ; idf_0 = 0 ; idv_0 = 0
+  CALL GETVAR_3D(idf_0, idv_0, cf_mm, 'e3w_0', 0, 0, E3W_3D)
+
+
+
+
+  !! *  Main loop on sections
+
+  DO jt = 1, nt !LB
+
+     PRINT *, 'Time record = ', jt
+
+     CALL GETVAR_3D(idf_t, idv_t,  cfilet, trim(cv_t), nt, jt, T_3D)
+     CALL GETVAR_3D(idf_s, idv_s,  cfilet, trim(cv_s),     nt, jt, S_3D)
+     CALL GETVAR_3D(idf_u, idv_u,  cfileu, trim(cv_u),     nt, jt, U_3D)
+     CALL GETVAR_3D(idf_v, idv_v,  cfilev, trim(cv_v),     nt, jt, V_3D)
+
+
+
+
+     DO jsec=1,nsection
+
+        PRINT *, 'Treating section '//TRIM(csection(jsec))
+
+        l_merid=.FALSE.
+        imin=imina(jsec) ; imax=imaxa(jsec) ; jmin=jmina(jsec) ; jmax=jmaxa(jsec)
+        IF (imin == imax ) THEN        ! meridional section
+           l_merid=.TRUE.
+           npts=jmax-jmin
+
+        ELSE IF ( jmin == jmax ) THEN  ! zonal section
+           npts=imax-imin
+
+        ELSE
+           PRINT *,' Section ',TRIM(csection(jsec)),' is neither zonal nor meridional :('
+           PRINT *,' We skip this section .'
+           CYCLE
+        ENDIF
+
+        !PRINT *, 'Allocating for jt, jsec =', jt, jsec
+        ALLOCATE ( zu(npts, npk), zt(npts,npk), zs(npts,npk) ,zsig(npts,0:npk) )
+        ALLOCATE ( eu(npts), e3(npts,npk), gdepu(npts, 0:npk), zmask(npts,npk) )
+        ALLOCATE ( tmpm(1,npts+1,2), tmpz(npts+1,1,2) )
+        ALLOCATE ( zwtrp(npts, nbins+1) , hiso(npts,nbins+1), zwtrpbin(npts,nbins) )
+
+        !END IF
+
+        !PRINT *, ' filling with 0...'
+        zt = 0. ; zs = 0. ; zu = 0. ; gdepu= 0. ; zmask = 0.  ; zsig=0.d0
+
+        IF (l_merid ) THEN   ! meridional section at i=imin=imax
+
+           !tmpm(:,:,1)=getvar(cf_mm, 'e2u', 1,1,npts, kimin=imin, kjmin=jmin+1)
+           !PRINT *, 'LOLO 1 =>', tmpm(:,:,1)
+           tmpm(1,:,1) = E2U_2D(imin,jmin+1:jmin+1+npts)
+           !PRINT *, 'LOLO 2 =>', tmpm(:,:,1)
+           !STOP
+
+           eu(:)=tmpm(1,1:npts,1)  ! metrics varies only horizontally
+           DO jk=1,npk
+              ! initiliaze gdepu to gdept()
+              gdepu(:,jk) = gdept(jk)
+
+              ! vertical metrics (PS case)
+              !tmpm(:,:,1)=getvar(cf_mm,'e3u_ps',jk,1,npts, kimin=imin, kjmin=jmin+1, ldiom=.TRUE.)
+              !PRINT *, 'LOLO1 =>', tmpm(:,:,1)
+              tmpm(1,:,1) = E3U_3D(imin,jmin+1:jmin+1+npts,jk)
+              !PRINT *, 'LOLO2 =>', tmpm(:,:,1)
+
+              e3(:,jk)=tmpm(1,1:npts,1)
+
+              !tmpm(:,:,1)=getvar(cf_mm,'e3w_ps',jk,1,npts, kimin=imin, kjmin=jmin+1, ldiom=.TRUE.)
+              !tmpm(:,:,2)=getvar(cf_mm,'e3w_ps',jk,1,npts, kimin=imin+1, kjmin=jmin+1, ldiom=.TRUE.)
+              tmpm(1,:,1) = E3W_3D(imin,  jmin+1:jmin+1+npts,jk)
+              tmpm(1,:,2) = E3W_3D(imin+1,jmin+1:jmin+1+npts,jk)
+
+
+              IF (jk >= 2 ) THEN
+                 DO ji=1,npts
+                    gdepu(ji,jk)= gdepu(ji,jk-1) + MIN(tmpm(1,ji,1), tmpm(1,ji,2))
+                 END DO
+              ENDIF
+
+              ! Normal velocity
+              tmpm(1,:,1) = U_3D(imin,jmin+1:jmin+1+npts,jk)
+
+              zu(:,jk)=tmpm(1,1:npts,1)
+
+              ! salinity and deduce umask for the section
+              tmpm(1,:,1) = S_3D(imin,  jmin+1:jmin+1+npts,jk)
+              tmpm(1,:,2) = S_3D(imin+1,jmin+1:jmin+1+npts,jk)
+
+              zmask(:,jk)=tmpm(1,1:npts,1)*tmpm(1,1:npts,2)
+              WHERE ( zmask(:,jk) /= 0._8 ) zmask(:,jk)=1._8
+              ! do not take special care for land value, as the corresponding velocity point is masked
+              zs(:,jk) = 0.5 * ( tmpm(1,1:npts,1) + tmpm(1,1:npts,2) )
+
+              ! limitation to 'wet' points
+              IF ( SUM(zs(:,jk))  == 0._8 ) 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,:,1) = T_3D(imin,  jmin+1:jmin+1+npts,jk)
+              tmpm(1,:,2) = T_3D(imin+1,jmin+1:jmin+1+npts,jk)
+
+              zt(:,jk) = 0.5 * ( tmpm(1,1:npts,1) + tmpm(1,1:npts,2) )
+
+           END DO
+
+
+
+        ELSE                   ! zonal section at j=jmin=jmax
+           !tmpz(npts,1,2)
+           !tmpz(:,:,1)=getvar(cf_mm, 'e1v', 1,npts,1,kimin=imin, kjmin=jmin)
+           !PRINT *, 'LOLO1 tmpz =>', tmpz(:,:,1)
+           tmpz(:,1,1) = E1V_2D(imin:imin+npts,jmin)
+           !PRINT *, 'LOLO2 tmpz =>', tmpz(:,:,1)
+
+           eu=tmpz(1:npts,1,1)
+           DO jk=1,npk
+              ! initiliaze gdepu to gdept()
+              gdepu(:,jk) = gdept(jk)
+
+              ! vertical metrics (PS case)
+              !tmpz(:,:,1)=getvar(cf_mm,'e3v_ps',jk, npts, 1, kimin=imin+1, kjmin=jmin, ldiom=.TRUE.)
+              tmpz(:,1,1) = E3V_3D(imin+1:imin+1+npts,jmin,jk)
+
+              e3(:,jk)=tmpz(1:npts,1,1)
+              !tmpz(:,:,1)=getvar(cf_mm,'e3w_ps',jk,npts,1, kimin=imin+1, kjmin=jmin, ldiom=.TRUE.)
+              !tmpz(:,:,2)=getvar(cf_mm,'e3w_ps',jk,npts,1, kimin=imin+1, kjmin=jmin+1, ldiom=.TRUE.)
+              tmpz(:,1,1) = E3W_3D(imin+1:imin+1+npts,jmin,  jk)
+              tmpz(:,1,2) = E3W_3D(imin+1:imin+1+npts,jmin+1,jk)
+
+              IF (jk >= 2 ) THEN
+                 DO ji=1,npts
+                    gdepu(ji,jk)= gdepu(ji,jk-1) + MIN(tmpz(ji,1,1), tmpz(ji,1,2))
+                 END DO
+              ENDIF
+
+              ! Normal velocity
+              tmpz(:,1,1) = V_3D(imin+1:imin+1+npts,jmin,  jk)
+              zu(:,jk)=tmpz(1:npts,1,1)
+
+              ! salinity and mask
+              tmpz(:,1,1) = S_3D(imin+1:imin+1+npts,jmin,  jk)
+              tmpz(:,1,2) = S_3D(imin+1:imin+1+npts,jmin+1,jk)
+
+              zmask(:,jk)=tmpz(1:npts,1,1)*tmpz(1:npts,1,2)
+              WHERE ( zmask(:,jk) /= 0._8 ) zmask(:,jk)=1._8
+              ! do not take special care for land value, as the corresponding velocity point is masked
+              zs(:,jk) = 0.5 * ( tmpz(1:npts,1,1) + tmpz(1:npts,1,2) )
+
+              ! limitation to 'wet' points
+              IF ( SUM(zs(:,jk))  == 0._8 ) 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,1) = T_3D(imin+1:imin+1+npts,jmin,  jk)
+              tmpz(:,1,2) = T_3D(imin+1:imin+1+npts,jmin+1,jk)
+
+              zt(:,jk) = 0.5 * ( tmpz(1:npts,1,1) + tmpz(1:npts,1,2) )
+           END DO
+
+        ENDIF  !(l_merid)
+
+        ! compute density only for wet points
+        zsig(:,1:nk)=sigma0( zt, zs, npts, nk)*zmask(:,1:nk)
+        zsig(:,0)=zsig(:,1)-1.e-4   ! dummy layer for easy interpolation
+
+
+
+        WRITE(cfor9000,'(a,i3,a)') '(i7,',npts,'f8.3)'
+        WRITE(cfor9001,'(a,i3,a)') '(i7,',npts,'f8.0)'
+        WRITE(cfor9002,'(a,i3,a)') '(f7.3,',npts,'f8.0)'
+        WRITE(cfor9003,'(a,i3,a)') '(f7.3,',npts,'f8.3)'
+        WRITE(cfor9004,'(a,i3,a)') '(f7.3,',npts+1,'f8.3)'
+
+
+
+
+
+        DO  jiso =1, nbins+1
+           sigma=sigma_lev(jiso)
+           DO ji=1,npts
+              hiso(ji,jiso) = gdept(npk)
+              DO jk=1,nk
+                 IF ( zsig(ji,jk) < sigma ) THEN
+                 ELSE
+                    ! interpolate between jk-1 and jk
+                    zalfa=(sigma - zsig(ji,jk-1)) / ( zsig(ji,jk) -zsig(ji,jk-1) )
+                    IF (ABS(zalfa) > 1.1 .OR. zalfa < 0 ) THEN   ! case zsig(0) = zsig(1)-1.e-4
+                       hiso(ji,jiso)= 0.
+                    ELSE
+                       hiso(ji,jiso)= gdepu(ji,jk)*zalfa + (1.-zalfa)* gdepu(ji,jk-1)
+                    ENDIF
+                    EXIT
+                 ENDIF
+              END DO
+           END DO
+        END DO
+
+
+        DO jiso = 1, nbins + 1
+           sigma=sigma_lev(jiso)
+           DO ji=1,npts
+              zwtrp(ji,jiso) = 0.d0
+              DO jk=1, nk-1
+                 IF ( gdepw(jk+1) < hiso(ji,jiso) ) THEN
+                    zwtrp(ji,jiso)= zwtrp(ji,jiso) + eu(ji)*e3(ji,jk)*zu(ji,jk)
+                 ELSE  ! last box ( fraction)
+                    zwtrp(ji,jiso)= zwtrp(ji,jiso) + eu(ji)*(hiso(ji,jiso)-gdepw(jk))*zu(ji,jk)
+                    EXIT  ! jk loop
+                 ENDIF
+              END DO
+           END DO
+        END DO
+
+        !DO jbin=1, nbins
+        !   sigma=sigma_lev(jbin)
+        !   DO ji=1, npts
+        !      zwtrpbin(ji,jbin) = zwtrp(ji,jbin+1) -  zwtrp(ji,jbin)
+        !   END DO
+        !   trpbin(jsec,jbin)=SUM(zwtrpbin(:,jbin) )
+        !END DO
+
+
+        DO jbin=1, nbins
+           sigma=sigma_lev(jbin)
+           DO ji=1, npts
+              zwtrpbin(ji,jbin) = zwtrp(ji,jbin+1) -  zwtrp(ji,jbin)
+           END DO
+           XOUT(jsec,jbin,jt)= REAL( SUM(zwtrpbin(:,jbin))/1.e6 , 4)
+        END DO
+
+
+        ! free memory for the next section
+        DEALLOCATE ( zu,zt, zs ,zsig ,gdepu, hiso, zwtrp, zwtrpbin )
+        DEALLOCATE ( eu, e3 ,tmpm, tmpz,zmask )
+
+        CLOSE(15)
+
+
+     END DO  !DO jsec=1,nsection
+
+  END DO   !DO jt = 1, nt
+
+
+
+  WRITE(cf_out, '(a,"/transport_by_sigma_class.nc")') trim(cd_out)
+
+  id_var_out(:) = 0
+
+
+  INQUIRE( FILE=cf_out, EXIST=lfncout )
+
+
+  IF ( .NOT. lfncout ) THEN
+
+     !! Creating file
+     PRINT *, ' Creating file '//trim(cf_out)//' !!!'
+     ierr = NF90_CREATE(cf_out, NF90_CLOBBER, idf_out)
+
+     ierr = NF90_DEF_DIM(idf_out, 'time',      NF90_UNLIMITED, idd_t)
+     ierr = NF90_DEF_DIM(idf_out, 'sigma_bins', nbins, idd_sbins)
+
+     ierr = NF90_DEF_VAR(idf_out, 'time',       NF90_DOUBLE, idd_t,     idv_time)
+
+     ierr = NF90_DEF_VAR(idf_out, 'sigma_bins', NF90_DOUBLE, idd_sbins, idv_sbins)
+     WRITE(cdum,'(f8.4)') dsigma
+     ierr = NF90_PUT_ATT(idf_out, idv_sbins, 'long_name', 'Center of sigma bin (dsigma = '//TRIM(cdum)//')')
+
+
+     DO jsec=1, nsection
+        ierr = NF90_DEF_VAR(idf_out, 'sigtrsp_'//TRIM(csection(jsec)), &
+             & NF90_FLOAT, (/idd_sbins,idd_t/), id_var_out(jsec))
+        ierr = NF90_PUT_ATT(idf_out, id_var_out(jsec), 'long_name', 'Transport by sigma class in section '//TRIM(csection(jsec)))
+        ierr = NF90_PUT_ATT(idf_out, id_var_out(jsec), 'units', 'Sv')
+     END DO
+
+     ierr = NF90_PUT_ATT(idf_out, NF90_GLOBAL, 'About', &
+        &   'Created by BaraKuda (cdfsigtrp.f90) => https://github.com/brodeau/barakuda')
+     ierr = NF90_ENDDEF(idf_out)
+     jt_pos = 0
+
+     ierr = NF90_PUT_VAR( idf_out, idv_sbins, sigma_lev_center(:))
+
+  ELSE
+
+     !! Opening already existing file
+     ierr = NF90_OPEN  (cf_out, NF90_WRITE, idf_out)
+
+     !! Need IDs of variables to append... NF90_INQ_VARID
+     DO jsec=1, nsection
+        ierr = NF90_INQ_VARID(idf_out, 'sigtrsp_'//TRIM(csection(jsec)), id_var_out(jsec))
+     END DO
+
+
+     ! Get ID of unlimited dimension
+     ierr = NF90_INQUIRE(idf_out, unlimitedDimId = idv_time)
+
+     ! Need to know jt_pos, record number of the last time record writen in the file
+     ierr = NF90_INQUIRE_DIMENSION(idf_out, idv_time, name=cdum, len=jt_pos)
+
+  END IF
+
+
+  WRITE(*,'("Going to write record ",i4.4," to ",i4.4," into ",a)') jt_pos+1, jt_pos+1+nt, trim(cf_out)
+
+  DO jt = 1, nt
+
+     ! Writing record jt for time vector and 1d fields:
+     ierr = NF90_PUT_VAR( idf_out, idv_time, (/ryear+1./12.*(REAL(jt)-1.+0.5)/), start=(/jt_pos+jt/), count=(/1/) )
+
+     DO jsec=1, nsection
+        ierr = NF90_PUT_VAR(idf_out, id_var_out(jsec), XOUT(jsec,:,jt), start=(/1,jt_pos+jt/), count=(/nbins,1/))
+     END DO
+
+  END DO
+
+  ierr = NF90_CLOSE(idf_out)
+
+  PRINT *, '  *** cdfsigtrp => '//TRIM(cf_out)//' written!'; PRINT *, ''
+
+CONTAINS
+
+
+  SUBROUTINE section_init(cdfile,cdsection,kimin,kimax,kjmin,kjmax,knumber)
+    IMPLICIT NONE
+    ! Arguments
+    !   INTEGER, DIMENSION(:),ALLOCATABLE :: kimin,kimax, kjmin,kjmax
+    INTEGER, INTENT(INOUT) :: knumber
+    INTEGER, DIMENSION(knumber) :: kimin,kimax, kjmin,kjmax
+    !   CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE :: cdsection
+    CHARACTER(LEN=256), DIMENSION(knumber) :: cdsection
+    CHARACTER(LEN=*), INTENT(IN) :: cdfile
+
+    ! Local variables
+    INTEGER :: ii, numit=10, jsec
+    CHARACTER(LEN=256) :: cline
+    LOGICAL :: lfirst
+
+    INTEGER :: idf_0=0, idv_0=0, idf_t=0, idv_t=0, idf_s=0, idv_s=0, &
+       &       idf_u=0, idv_u=0, idf_v=0, idv_v=0
+
+
+
+
+
+    lfirst=.FALSE.
+    IF ( knumber == 0 ) lfirst=.TRUE.
+
+    OPEN(numit, FILE=cdfile, STATUS='old')
+    REWIND(numit)
+    ii=0
+
+    DO
+       READ(numit,'(a)') cline
+       IF (INDEX(cline,'EOF') == 0 ) THEN
+          READ(numit,*)    ! skip one line
+          ii = ii + 1
+       ELSE
+          EXIT
+       ENDIF
+    END DO
+
+
+    knumber=ii
+    IF ( lfirst ) RETURN
+    !   ALLOCATE( cdsection(knumber) )
+    !   ALLOCATE( kimin(knumber), kimax(knumber), kjmin(knumber), kjmax(knumber) )
+    REWIND(numit)
+    DO jsec=1,knumber
+       READ(numit,'(a)') cdsection(jsec)
+       READ(numit,*) kimin(jsec), kimax(jsec), kjmin(jsec), kjmax(jsec)
+    END DO
+
+    CLOSE(numit)
+
+  END SUBROUTINE section_init
+  
+
+END PROGRAM cdfsigtrp

+ 574 - 0
cdftools_light/src/cdftransport_test_sign.f90

@@ -0,0 +1,574 @@
+PROGRAM cdftransportiz
+
+   !!---------------------------------------------------------------------
+   !!               ***  PROGRAM cdftransportiz  ***
+   !!
+   !!  **  Purpose: Compute Transports across a section
+   !!               PARTIAL STEPS version
+   !!
+   !!  **  Method: Try to avoid 3 d arrays.
+   !!             The begining and end point of the section are given in term of f-points index.
+   !!             This program computes the transport across this section for
+   !!               (1) Mass transport ( Sv)
+   !!             The transport is > 0 left handside of the line
+   !!             This program use a zig-zag line going through U and V-points.
+   !!             It takes as input : VT files, gridU, gridV files.
+   !!             The mesh_mask.nc, mesh_hzr.nc are required.
+   !!             It is convenient to use an ASCII file as the standard input to give
+   !!             the name and the ii0 ii1 ij0 ij1 for each section required
+   !!             The last name of this ASCII file must be EOF
+   !!
+   !!
+   !! history :
+   !!   Original :  J.M. Molines (jan. 2005)
+   !!               J.M. Molines Apr 2005 : use modules
+   !!               J.M. Molines Apr 2007 : merge with Julien Jouanno version (std + file output)
+   !!               R. Dussin (Jul. 2009) : add cdf output
+   !!---------------------------------------------------------------------
+   !!  $Rev: 257 $
+   !!  $Date: 2009-07-27 18:25:04 +0200 (Mon, 27 Jul 2009) $
+   !!  $Id: cdftransportiz.f90 257 2009-07-27 16:25:04Z forge $
+   !!--------------------------------------------------------------
+   !! * Modules used
+
+   USE netcdf
+
+   USE cdfio
+   USE io_ezcdf
+
+
+   !! * Local variables
+   IMPLICIT NONE
+
+   LOGICAL, PARAMETER :: l_save_broken_lines = .FALSE. !lolo
+
+   INTEGER :: nclass   !: number of depth class
+   INTEGER ,DIMENSION (:),ALLOCATABLE ::  imeter  !: limit beetween depth level, in m (nclass -1)
+   CHARACTER(len=64), DIMENSION (:),ALLOCATABLE ::  cdepths
+   INTEGER ,DIMENSION (:),ALLOCATABLE :: ilev0,ilev1 !: limit in levels  ! nclass
+   INTEGER   :: jk, jc, jj, jt                  !: dummy loop index !LB
+   INTEGER   :: narg, iargc, istatus                         !: command line
+   INTEGER   :: npiglo,npjglo, npk, nt               !: size of the domain !LB
+   INTEGER   :: ii0, ii1, ij0, ij1, ik
+   INTEGER   :: numin  = 16
+
+   INTEGER(KIND=4) :: idirx, idiry   ! sense of description of the section
+
+   ! broken line stuff
+   INTEGER, PARAMETER :: jpseg=10000
+   INTEGER :: i, j
+   INTEGER :: n,nn,k, jseg
+   INTEGER :: norm_u, norm_v, iist, ijst
+
+   REAL(4) ::  rxi0,ryj0, rxi1, ryj1
+
+   REAL(8) :: ref_temp=0, rU, rV
+
+   REAL(4) ::   ai,bi, aj,bj,d
+   REAL(4) ::    rxx(jpseg),ryy(jpseg)
+   REAL(4), DIMENSION(jpseg) :: gla, gphi
+
+   REAL(8), DIMENSION(jpseg) :: voltrp
+   REAL(8)                   :: voltrpsum
+   COMPLEX yypt(jpseg), yypti
+
+   REAL(4), DIMENSION (:,:),   ALLOCATABLE ::         e1v, e3v ,gphiv, zv
+   REAL(4), DIMENSION (:,:),   ALLOCATABLE ::         e2u, e3u ,gphiu, zu
+   REAL(4), DIMENSION (:,:),   ALLOCATABLE ::         glamu, glamv
+   REAL(4), DIMENSION (:),     ALLOCATABLE ::         gdepw, gdept
+   REAL(4)                                 ::   rd1, rd2
+
+   REAL(8),   DIMENSION (:,:), ALLOCATABLE :: zwku,zwkv
+   REAL(8),   DIMENSION (:,:,:), ALLOCATABLE :: ztrpu, ztrpv
+
+   CHARACTER(len=8) :: ctest, crt, cu, cv
+
+   CHARACTER(LEN=256) :: conf_tag, cf_u, cf_v, csection, cf_broken_line,  &
+      &                cfilvtrp='vtrp.txt', cfilhtrp='htrp.txt', cfilstrp='strp.txt'
+
+   CHARACTER(LEN=256) :: cf_mm='mesh_mask.nc', cdum
+   CHARACTER(LEN=256) ,DIMENSION(4)   :: cvarname   !: array of var name for output
+
+   INTEGER :: nxtarg
+
+   LOGICAL :: &
+      &     lcontinue = .TRUE.
+
+   CHARACTER(LEN=256) :: ctim
+
+
+
+   REAL(4), DIMENSION(:,:,:), ALLOCATABLE :: U_3D, V_3D, E3V_3D, E3U_3D
+
+   INTEGER :: idf_u=0, idv_u=0, idf_v=0, idv_v=0, &
+      &       idf_0=0, idv_0=0
+
+
+   !! LOLO:
+   LOGICAL :: lfncout = .false.
+   CHARACTER(LEN=256) :: cd_out = '.', cf_out
+   CHARACTER(LEN=64)  :: cv_u, cv_v, cv_dum
+   REAL :: ryear
+   INTEGER :: ierr, jt_pos, idf_out, idd_t, idv_time
+   INTEGER, DIMENSION(:)    , ALLOCATABLE :: id_volu
+   REAL(4), DIMENSION(:,:,:), ALLOCATABLE :: X_trsp   ! lolo
+   !! LOLO.
+
+
+
+   !!  Read command line and output usage message if not compliant.
+   narg= iargc()
+   IF ( narg < 2  ) THEN
+      PRINT *,' Usage : cdftransportiz <U> <V> '
+      PRINT *,' Files mesh_mask.nc must be in te current directory'
+      STOP
+   ENDIF
+
+   CALL getarg (1, cu)    ; READ(cu,*) rU
+   CALL getarg (2, cv)    ; READ(cv,*) rV
+   PRINT *, ''
+   PRINT *, ' U and V =>', rU, rV
+   PRINT *, ''
+
+   nxtarg=7
+   !nclass = narg -nxtarg + 1
+   nclass = 1
+
+
+   ALLOCATE (  cdepths(0:nclass), imeter(nclass -1), ilev0(nclass), ilev1(nclass) )
+
+   cdepths(0) = '0'
+   cdepths(nclass) = 'botto'
+   DO jk=1, nclass -1
+      CALL getarg(nxtarg+jk,cdepths(jk))
+      READ(cdepths(jk),*) imeter(jk)
+   END DO
+
+   npiglo= getdim (cf_mm,'x')
+   npjglo= getdim (cf_mm,'y')
+   npk   = getdim (cf_mm,'z')
+
+   ctim = 'none'
+   nt    = 1
+
+   PRINT *, 'npiglo=', npiglo
+   PRINT *, 'npjglo=', npjglo
+   PRINT *, 'npk   =', npk
+   PRINT *, 'nt    =', nt !LB
+   PRINT *, ''
+
+   !ALLOCATE( U_3D(npiglo,npjglo,npk) , V_3D(npiglo,npjglo,npk) , &
+   ALLOCATE( E3V_3D(npiglo,npjglo,npk) , E3U_3D(npiglo,npjglo,npk) )
+
+
+   !! Lolo: allocating array to contain transports:
+   ALLOCATE( X_trsp(3,nt,nclass) ) ; ! 3 transports, nt values, nclass levels
+   ALLOCATE( id_volu(0:nclass) )
+
+   ! Allocate arrays
+   ALLOCATE( zu (npiglo,npjglo) )
+   ALLOCATE( zv (npiglo,npjglo) )
+   !
+   ALLOCATE ( zwku (npiglo,npjglo) )
+   ALLOCATE ( zwkv (npiglo,npjglo) )
+   !
+   ALLOCATE ( ztrpu (npiglo,npjglo,nclass), ztrpv (npiglo,npjglo,nclass))
+   !
+   ALLOCATE ( e1v(npiglo,npjglo),e3v(npiglo,npjglo))
+   ALLOCATE ( e2u(npiglo,npjglo),e3u(npiglo,npjglo))
+   !
+   ALLOCATE ( gphiu(npiglo,npjglo),  gphiv(npiglo,npjglo) )
+   ALLOCATE ( glamu(npiglo,npjglo),  glamv(npiglo,npjglo) )
+   ALLOCATE ( gdepw(npk), gdept(npk) )
+   !
+
+   e1v(:,:) = getvar(cf_mm, 'e1v', 1,npiglo,npjglo)
+   e2u(:,:) = getvar(cf_mm, 'e2u', 1,npiglo,npjglo)
+
+   glamv(:,:) =  getvar(cf_mm, 'glamv', 1,npiglo,npjglo)
+   glamu(:,:) =  getvar(cf_mm, 'glamu', 1,npiglo,npjglo)
+
+   gphiv(:,:) = getvar(cf_mm, 'gphiv', 1,npiglo,npjglo)
+   gphiu(:,:) = getvar(cf_mm, 'gphiu', 1,npiglo,npjglo)
+
+   gdepw(:) = getvare3(cf_mm, 'gdepw_1d',npk)
+   gdept(:) = getvare3(cf_mm, 'gdept_1d',npk)
+
+
+
+
+   DO WHILE ( lcontinue )
+
+      OPEN(numin, FILE='transportiz.dat', status='old')
+      READ(numin,'(a)') csection
+      IF (TRIM(csection) == 'EOF' ) THEN
+         CLOSE(numin)
+         lcontinue = .FALSE.
+         EXIT
+      END IF
+
+      IF ( .NOT. lcontinue ) EXIT
+
+      READ(numin,*) ii0, ii1, ij0, ij1
+      WRITE(*,'(" *** Section = ",a," (",i4.4,", "i4.4,", "i4.4,", "i4.4,") ***")') TRIM(csection), ii0, ii1, ij0, ij1
+      !PRINT*, ' =>', ii0, ii1, ij0, ij1
+
+      !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
+
+
+      READ(numin,'(a)') ctest
+      IF (TRIM(ctest) == 'ref_temp' ) THEN
+         !READ(numin,'(f)') ref_temp
+         READ(numin,*) ref_temp
+         PRINT *, '  => reference temperature for heat transport is ', ref_temp
+      ELSE
+         BACKSPACE(numin)
+      END IF
+
+      WRITE(crt,'(f7.4)') ref_temp
+
+
+      ! get e3u, e3v  at all levels
+      CALL GETVAR_3D(idf_0, idv_0, cf_mm, 'e3v_0', 0, 0, E3V_3D)
+      idf_0 = 0. ; idv_0 = 0.
+      CALL GETVAR_3D(idf_0, idv_0, cf_mm, 'e3u_0', 0, 0, E3U_3D)
+
+
+
+      DO jt = 1, nt !lolo
+         !! -------------
+         ! look for nearest level to imeter
+         ik = 1
+         ilev0(1)      = 1
+         ilev1(nclass) = npk-1
+
+         DO jk = 1, nclass -1
+            DO WHILE ( gdepw(ik)  < imeter(jk) )
+               ik = ik +1
+            END DO
+
+            rd1= ABS(gdepw(ik-1) - imeter(jk) )
+            rd2= ABS(gdepw(ik) - imeter(jk) )
+            IF ( rd2 < rd1 ) THEN
+               ilev1(jk) = ik -1  ! t-levels
+               ilev0(jk+1) = ik
+            ELSE
+               ilev1(jk) = ik -2  ! t-levels
+               ilev0(jk+1) = ik -1
+            END IF
+         END DO
+
+
+
+         !! compute the transport
+         ztrpu (:,:,:)= 0
+         ztrpv (:,:,:)= 0
+
+         DO jc = 1, nclass
+
+            DO jk = ilev0(jc),ilev1(jc)
+
+               ! Get velocities, temperature and salinity fluxes at jk
+               zu (:,:)= rU
+               zv (:,:)= rV
+
+               e3v(:,:) = E3V_3D(:,:,jk)
+               e3u(:,:) = E3U_3D(:,:,jk)
+
+               zwku (:,:) = zu (:,:)*e2u(:,:)*e3u(:,:)
+               zwkv (:,:) = zv (:,:)*e1v(:,:)*e3v(:,:)
+
+               ! integrates vertically
+               ztrpu (:,:,jc) = ztrpu (:,:,jc) + zwku (:,:)
+               ztrpv (:,:,jc) = ztrpv (:,:,jc) + zwkv (:,:)
+
+            END DO  ! loop to next level
+         END DO    ! next class
+
+
+
+         IF (jt == 1) THEN
+
+            IF ( nclass > 3 ) THEN
+               PRINT *, 'LOLO=> cdftransportiz.f90 only supports 2 depths currently!!!'
+            END IF
+
+
+            !! Find the broken line between P1 (ii0,ij0) and P2 (ii1, ij1)
+            !! ---------------------------------------------------------------
+            ! ... Initialization
+            !i0=ii0; j0=ij0; i1=ii1;  j1=ij1
+            rxi1=ii1;  ryj1=ij1; rxi0=ii0; ryj0=ij0
+
+            ! .. Compute equation:  ryj = aj rxi + bj
+            IF ( (rxi1 -rxi0) /=  0 ) THEN
+               aj = (ryj1 - ryj0 ) / (rxi1 -rxi0)
+               bj = ryj0 - aj * rxi0
+            ELSE
+               aj=10000.
+               bj=0.
+            END IF
+
+            ! .. Compute equation:  rxi = ai ryj + bi
+            IF ( (ryj1 -ryj0) /=  0 ) THEN
+               ai = (rxi1 - rxi0 ) / ( ryj1 -ryj0 )
+               bi = rxi0 - ai * ryj0
+            ELSE
+               ai=10000.
+               bi=0.
+            END IF
+
+            ! ..  Compute the integer pathway:
+            n=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 and remember it has been swapped
+               IF (ii1 <  ii0 ) THEN
+                  i  = ii0 ; j  = ij0
+                  ii0 = ii1 ; ij0 = ij1
+                  ii1 = i  ; ij1 = j
+               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 j point on the line crossing at i
+               DO i=ii0,ii1
+                  n=n+1
+                  IF (n > jpseg) STOP 'n > jpseg !'
+                  j=NINT(aj*i + bj )
+                  yypt(n) = CMPLX(i,j)
+               END DO
+            ELSE
+
+               ! ... Here, the best line is x(y)
+               ! ... If ij1 < ij0 swap points and remember it has been swapped
+               IF (ij1 <  ij0 ) THEN
+                  i  = ii0 ; j  = ij0
+                  ii0 = ii1 ; ij0 = ij1
+                  ii1 = i  ; ij1 = j
+               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 i point on the line crossing at j
+               DO j=ij0,ij1
+                  n=n+1
+                  IF (n > jpseg) STOP 'n>jpseg !'
+                  i=NINT(ai*j + bi)
+                  yypt(n) = CMPLX(i,j)
+               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 k=2,n
+               ! .. distance between 2 neighbour points
+               d=ABS(yypt(k)-yypt(k-1))
+               ! .. intermediate points required if d > 1
+               IF ( d > 1 ) THEN
+                  CALL interm_pt(yypt,k,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(k))
+               ryy(nn)=IMAG(yypt(k))
+            END DO
+
+            IF ( l_save_broken_lines ) THEN
+               !! LOLO: We want to save the Broken line in an ascci file for further use:
+               WRITE(cf_broken_line,'("broken_line_",a,".dat")') trim(csection)
+               OPEN(UNIT=19, FILE=trim(cf_broken_line), FORM='FORMATTED', RECL=256, STATUS='unknown')
+               PRINT *, 'Saving broken line into file ', trim(cf_broken_line)
+               WRITE(19,*)'#       ji          jj'
+               DO jseg = 1, nn
+                  ii0=rxx(jseg)
+                  ij0=ryy(jseg)
+                  WRITE(19,*) ii0, ij0
+               END DO
+               CLOSE(19)
+               PRINT *, ''
+            END IF
+
+         END IF !* IF ( jt == 1 )
+
+
+
+
+
+         DO jc=1,nclass
+
+            voltrpsum = 0.
+
+            DO jseg = 1, nn-1
+               ii0=rxx(jseg)
+               ij0=ryy(jseg)
+               IF ( rxx(jseg) ==  rxx(jseg+1) ) THEN
+                  gla(jseg)=glamu(ii0,ij0+ijst)   ; gphi(jseg)=gphiu(ii0,ij0+ijst)
+                  voltrp(jseg)= ztrpu (ii0,ij0+ijst,jc)*norm_u
+               ELSE IF ( ryy(jseg) == ryy(jseg+1) ) THEN
+                  gla(jseg)=glamv(ii0+iist,ij0)  ;  gphi(jseg)=gphiv(ii0+iist,ij0)
+                  voltrp(jseg)=ztrpv (ii0+iist,ij0,jc)*norm_v
+               ELSE
+                  PRINT *,' ERROR :',  rxx(jseg),ryy(jseg),rxx(jseg+1),ryy(jseg+1)
+               END IF
+               voltrpsum = voltrpsum+voltrp(jseg)
+            END DO   ! next segment
+
+
+            X_trsp(:,jt,jc) = (/ REAL(voltrpsum/1.e6,4), REAL(0.,4), REAL(0.,4) /) ! lolo
+
+
+         END DO ! next class
+
+      END DO ! loop on jt
+
+
+      PRINT *, '  => Volume transport =', X_trsp(1,:,:)
+      PRINT *, ''
+
+   END DO ! loop on sections...
+
+   DEALLOCATE( X_trsp ) !lolo
+
+CONTAINS
+
+
+   SUBROUTINE interm_pt (ydpt,k,pai,pbi,paj,pbj,ydpti)
+      !! -----------------------------------------------------
+      !!           SUBROUTINE INTERM_PT
+      !!           ********************
+      !!
+      !!   PURPOSE:
+      !!   --------
+      !!     Find the best intermediate points on a pathway.
+      !!
+      !!    ARGUMENTS:
+      !!    ----------
+      !!      ydpt : complex vector of the positions of the nearest points
+      !!         k : 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
+      !!
+      !!    AUTHOR:
+      !!    -------
+      !!      19/07/1999 : Jean-Marc MOLINES
+      !!      14/01/2005 : J M M in F90
+      !!
+      !!--------------------------------------------------------------
+      !!
+      !! 0. Declarations:
+      !! ----------------
+      IMPLICIT NONE
+      COMPLEX, INTENT(in) :: ydpt(*)
+      COMPLEX, INTENT(out) :: ydpti
+      REAL(4), INTENT(IN) ::  pai,pbi,paj,pbj
+      INTEGER ,INTENT(in) :: k
+      ! ... local
+      COMPLEX :: ylptmp1, ylptmp2
+      REAL(4) ::  za0,zb0,za1,zb1,zd1,zd2
+      REAL(4) ::  zxm,zym
+      REAL(4) ::  zxp,zyp
+      !!
+      !! 1. Compute intermediate points
+      !! ------------------------------
+      !
+      ! ... Determines whether we use y(x) or x(y):
+      IF (ABS(paj) <=  1) THEN
+         ! ..... y(x)
+         ! ... possible intermediate points:
+         ylptmp1=ydpt(k-1)+(1.,0.)
+         ylptmp2=ydpt(k-1)+CMPLX(0.,SIGN(1.,paj))
+         !
+         ! ... M is the candidate point:
+         zxm=REAL(ylptmp1)
+         zym=IMAG(ylptmp1)
+         za0=paj
+         zb0=pbj
+         !
+         za1=-1./za0
+         zb1=zym - za1*zxm
+         ! ... P is the projection of M on the strait line
+         zxp=-(zb1-zb0)/(za1-za0)
+         zyp=za0*zxp + zb0
+         ! ... zd1 is the distance MP
+         zd1=(zxm-zxp)*(zxm-zxp) + (zym-zyp)*(zym-zyp)
+         !
+         ! ... M is the candidate point:
+         zxm=REAL(ylptmp2)
+         zym=IMAG(ylptmp2)
+         za1=-1./za0
+         zb1=zym - za1*zxm
+         ! ... P is the projection of M on the strait line
+         zxp=-(zb1-zb0)/(za1-za0)
+         zyp=za0*zxp + zb0
+         ! ... zd2 is the distance MP
+         zd2=(zxm-zxp)*(zxm-zxp) + (zym-zyp)*(zym-zyp)
+         ! ... chose the smallest (zd1,zd2)
+         IF (zd2 <=  zd1) THEN
+            ydpti=ylptmp2
+         ELSE
+            ydpti=ylptmp1
+         END IF
+         !
+      ELSE
+         !
+         ! ... x(y)
+         ylptmp1=ydpt(k-1)+CMPLX(SIGN(1.,pai),0.)
+         ylptmp2=ydpt(k-1)+(0.,1.)
+         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 cdftransportiz

+ 833 - 0
cdftools_light/src/cdftransportiz.f90

@@ -0,0 +1,833 @@
+
+
+PROGRAM cdftransportiz
+
+   !!---------------------------------------------------------------------
+   !!               ***  PROGRAM cdftransportiz  ***
+   !!
+   !!  **  Purpose: Compute Transports across a section
+   !!               PARTIAL STEPS version
+   !!
+   !!  **  Method: Try to avoid 3 d arrays.
+   !!             The begining and end point of the section are given in term of f-points index.
+   !!             This program computes the transport across this section for
+   !!               (1) Mass transport ( Sv)
+   !!               (2) Heat Transport (PW)
+   !!               (3) Salt Transport (kT/sec)
+   !!               (4) Freshwater Transport (Sv)
+   !!             The transport is > 0 left handside of the line
+   !!             This program use a zig-zag line going through U and V-points.
+   !!             It takes as input : VT files, gridU, gridV files.
+   !!             The mesh_mask.nc, mesh_hzr.nc are required.
+   !!             It is convenient to use an ASCII file as the standard input to give
+   !!             the name and the ii0 ii1 ij0 ij1 for each section required
+   !!             The last name of this ASCII file must be EOF
+   !!
+   !!
+   !! history :
+   !!   Original :  J.M. Molines (jan. 2005)
+   !!               J.M. Molines Apr 2005 : use modules
+   !!               J.M. Molines Apr 2007 : merge with Julien Jouanno version (std + file output)
+   !!               R. Dussin (Jul. 2009) : add cdf output
+   !!---------------------------------------------------------------------
+   !!  $Rev: 257 $
+   !!  $Date: 2009-07-27 18:25:04 +0200 (Mon, 27 Jul 2009) $
+   !!  $Id: cdftransportiz.f90 257 2009-07-27 16:25:04Z forge $
+   !!--------------------------------------------------------------
+   !! * Modules used
+
+   USE netcdf
+
+   USE cdfio
+   USE io_ezcdf
+
+   IMPLICIT NONE
+
+   REAL(8) :: &
+      &        ref_temp0 = 0.,     & ! reference temperature (in Celsius) for the transport of heat
+      &        ref_sali0 = 34.8,   & ! reference salinity    (in PSU) for the transport of salt
+      &        ref_temp, ref_sali, &
+      &        rU, rV
+   CHARACTER(len=128) :: ctest, c0, c1, c2, cref1='0.', cref2='34.8'
+
+
+   CHARACTER(len=256) :: cf_sections
+
+
+   LOGICAL, PARAMETER :: l_save_broken_lines = .FALSE.
+
+   INTEGER :: nclass   !: number of depth class
+   INTEGER ,DIMENSION (:),ALLOCATABLE ::  imeter  !: limit beetween depth level, in m (nclass -1)
+   CHARACTER(len=64), DIMENSION (:),ALLOCATABLE ::  cdepths
+   INTEGER ,DIMENSION (:),ALLOCATABLE :: ilev0,ilev1 !: limit in levels  ! nclass
+   INTEGER   :: jk, jc, jj, jt                  !: dummy loop index !LB
+   INTEGER   :: narg, iargc, istatus                         !: command line
+   INTEGER   :: npiglo,npjglo, npk, nt               !: size of the domain !LB
+   INTEGER   :: ii0, ii1, ij0, ij1, ik, ispace
+   INTEGER   :: numin  = 16
+
+   INTEGER(KIND=4) :: idirx, idiry   ! sense of description of the section
+
+   ! broken line stuff
+   INTEGER, PARAMETER :: jpseg=10000
+   INTEGER :: i, j
+   INTEGER :: n,nn,k, jseg
+   INTEGER :: norm_u, norm_v, iist, ijst
+
+   REAL(4) ::  rxi0,ryj0, rxi1, ryj1
+
+   REAL(4) ::   ai,bi, aj,bj,d
+   REAL(4) ::    rxx(jpseg),ryy(jpseg)
+   REAL(4), DIMENSION(jpseg) :: gla, gphi
+
+   REAL(8), DIMENSION(jpseg) :: voltrp, heatrp, saltrp
+   REAL(8)                   :: voltrpsum, heatrpsum, saltrpsum, frwtrpsum
+   COMPLEX yypt(jpseg), yypti
+
+   REAL(4), DIMENSION (:,:),   ALLOCATABLE ::         e1v, e3v ,gphiv, zv, zvt, zvs !: mask, metrics
+   REAL(4), DIMENSION (:,:),   ALLOCATABLE ::         e2u, e3u ,gphiu, zu, zut, zus !: mask, metrics
+   REAL(4), DIMENSION (:,:),   ALLOCATABLE ::         glamu, glamv
+   REAL(4), DIMENSION (:),     ALLOCATABLE ::         gdepw, gdept
+   REAL(4)                                 ::   rd1, rd2
+
+   REAL(8),   DIMENSION (:,:), ALLOCATABLE :: zwku,zwkv,    zwkut,zwkvt,   zwkus,zwkvs
+   REAL(8),   DIMENSION (:,:,:), ALLOCATABLE :: ztrpu, ztrpv, ztrput,ztrpvt, ztrpus,ztrpvs
+
+   CHARACTER(LEN=256) :: conf_tag, cf_vt , cf_u, cf_v, csection, cf_broken_line,  &
+      &                cfilvtrp='vtrp.txt', cfilhtrp='htrp.txt', cfilstrp='strp.txt'
+
+   CHARACTER(LEN=256) :: cf_mm='mesh_mask.nc', cdum
+   CHARACTER(LEN=256) ,DIMENSION(4)   :: cvarname   !: array of var name for output
+
+   INTEGER :: nxtarg
+
+   LOGICAL :: &
+      &     leiv  = .TRUE., &    !: weather to use Eddy Induced velocity from GM90
+      &     lcontinue = .TRUE.
+
+   CHARACTER(LEN=256) :: ctim
+
+   ! constants
+   !lolo: # The density of seawater is about 1025 kg/m^3 and the specific heat is about 4000 J/(kg C)
+   REAL(4)   ::  rau0=1025.,  rcp=3990.
+
+
+   REAL(4), DIMENSION(:,:,:), ALLOCATABLE :: U_3D, V_3D, UEIV_3D, VEIV_3D, UT_3D, VT_3D, US_3D, VS_3D, E3V_3D, E3U_3D
+
+   INTEGER :: idf_u=0, idv_u=0, idf_v=0, idv_v=0, idf_ueiv=0, idv_ueiv=0, idf_veiv=0, idv_veiv=0, &
+      &     idf_ut=0, idv_ut=0, idf_vt=0, idv_vt=0, &
+      &     idf_us=0, idv_us=0, idf_vs=0, idv_vs=0, idf_0=0, idv_0=0
+
+
+   LOGICAL :: lfncout = .false.
+   CHARACTER(LEN=256) :: cd_out = '.', cf_out
+   CHARACTER(LEN=64)  :: cv_u, cv_v, cv_ueiv, cv_veiv, cv_dum
+   REAL :: ryear
+   INTEGER :: ierr, jt_pos, idf_out, idd_t, idv_time
+   INTEGER, DIMENSION(:)    , ALLOCATABLE :: id_volu, id_heat, id_salt, id_frwt
+   REAL(4), DIMENSION(:,:,:), ALLOCATABLE :: X_trsp   ! lolo
+
+
+
+   !!  Read command line and output usage message if not compliant.
+   narg= iargc()
+   IF ( narg < 8  ) THEN
+      PRINT *,' Usage: cdftransportiz <file_section_ASCII> <CONFTAG> <nameU> <nameV> \\'
+      PRINT *,'                       <nameUeiv> <nameVeiv> <year> <DIROUT> (<z1> <z2>)'
+      PRINT *,''
+      PRINT *,'    => files are: <CONFTAG>_VT.nc <CONFTAG>_grid_U.nc <CONFTAG>_grid_V.nc'
+      PRINT *,' If eddy-induced velocity is not relevant, specify "0" "0" for <nameUeiv> <nameVeiv>'
+      PRINT *,' Files mesh_mask.nc must be in te current directory'
+      PRINT *, ''
+      PRINT *,' In your transportiz.dat, you can specify the reference temperature and salinity to use'
+      PRINT *,' to compute transports (defaults are 0. deg.C and 34.8 PSU).'
+      PRINT *,' below the line with i,j coordinates, specify "ref_temp_sali: T0 S0". Ex:'
+      PRINT *,'FRAM-STRAIT'
+      PRINT *,'279 268 272 272'
+      PRINT *,'ref_temp_sali: -0.5 35.'
+      PRINT *,'...'
+      PRINT *,''
+      STOP
+   ENDIF
+
+   CALL getarg (1, cf_sections)
+   CALL getarg (2, conf_tag)
+   CALL getarg (3, cv_u)
+   CALL getarg (4, cv_v)
+   CALL getarg (5, cv_ueiv)
+   CALL getarg (6, cv_veiv)
+   CALL getarg (7, cdum)    ; READ(cdum,*) ryear
+   CALL getarg (8, cd_out)
+
+   nxtarg=8
+   nclass = narg -nxtarg + 1
+
+
+
+   leiv = .TRUE.
+   IF ( (trim(cv_ueiv) == '0').AND.(trim(cv_veiv) == '0') ) THEN
+      leiv = .FALSE.
+      PRINT *, ' Not taking eddy-induced velocity into account!'
+   ELSE
+      PRINT *, ' Taking eddy-induced velocity into account using '//trim(cv_ueiv)//' and '//trim(cv_veiv)
+   END IF
+
+
+   WRITE(cf_vt, '(a,"_VT.nc")')     trim(conf_tag)
+   WRITE(cf_u,  '(a,"_grid_U.nc")') trim(conf_tag)
+   WRITE(cf_v,  '(a,"_grid_V.nc")') trim(conf_tag)
+
+   ALLOCATE (  cdepths(0:nclass), imeter(nclass -1), ilev0(nclass), ilev1(nclass) )
+
+   cdepths(0) = '0'
+   cdepths(nclass) = 'botto'
+   DO jk=1, nclass -1
+      CALL getarg(nxtarg+jk,cdepths(jk))
+      READ(cdepths(jk),*) imeter(jk)
+   END DO
+
+   npiglo= getdim (cf_vt,'x')
+   npjglo= getdim (cf_vt,'y')
+   npk   = getdim (cf_vt,'depth')
+
+   ctim = 'none'
+   nt    = getdim (cf_vt,'time',cdtrue=ctim,kstatus=istatus) !LB
+
+   PRINT *, 'npiglo=', npiglo
+   PRINT *, 'npjglo=', npjglo
+   PRINT *, 'npk   =', npk
+   PRINT *, 'nt    =', nt !LB
+   PRINT *, ''
+
+   ALLOCATE( U_3D(npiglo,npjglo,npk) , V_3D(npiglo,npjglo,npk) , UT_3D(npiglo,npjglo,npk) , VT_3D(npiglo,npjglo,npk) , &
+      &    US_3D(npiglo,npjglo,npk) , VS_3D(npiglo,npjglo,npk), E3V_3D(npiglo,npjglo,npk) , E3U_3D(npiglo,npjglo,npk) )
+
+   IF ( leiv ) ALLOCATE( UEIV_3D(npiglo,npjglo,npk) , VEIV_3D(npiglo,npjglo,npk) )
+
+
+   !! Lolo: allocating array to contain transports:
+   ALLOCATE( X_trsp(4,nt,nclass) ) ; ! 3 transports, nt values, nclass levels
+   ALLOCATE( id_volu(0:nclass), id_heat(0:nclass), id_salt(0:nclass), id_frwt(0:nclass) )
+
+   ! Allocate arrays
+   ALLOCATE( zu (npiglo,npjglo), zut(npiglo,npjglo), zus(npiglo,npjglo) )
+   ALLOCATE( zv (npiglo,npjglo), zvt(npiglo,npjglo), zvs(npiglo,npjglo) )
+   !
+   ALLOCATE ( zwku (npiglo,npjglo), zwkut(npiglo,npjglo), zwkus(npiglo,npjglo) )
+   ALLOCATE ( zwkv (npiglo,npjglo), zwkvt(npiglo,npjglo), zwkvs(npiglo,npjglo) )
+   !
+   ALLOCATE ( ztrpu (npiglo,npjglo,nclass), ztrpv (npiglo,npjglo,nclass))
+   ALLOCATE ( ztrput(npiglo,npjglo,nclass), ztrpvt(npiglo,npjglo,nclass))
+   ALLOCATE ( ztrpus(npiglo,npjglo,nclass), ztrpvs(npiglo,npjglo,nclass))
+   !
+   ALLOCATE ( e1v(npiglo,npjglo),e3v(npiglo,npjglo))
+   ALLOCATE ( e2u(npiglo,npjglo),e3u(npiglo,npjglo))
+   !
+   ALLOCATE ( gphiu(npiglo,npjglo),  gphiv(npiglo,npjglo) )
+   ALLOCATE ( glamu(npiglo,npjglo),  glamv(npiglo,npjglo) )
+   ALLOCATE ( gdepw(npk), gdept(npk) )
+   !
+
+   e1v(:,:) = getvar(cf_mm, 'e1v', 1,npiglo,npjglo)
+   e2u(:,:) = getvar(cf_mm, 'e2u', 1,npiglo,npjglo)
+
+   glamv(:,:) =  getvar(cf_mm, 'glamv', 1,npiglo,npjglo)
+   glamu(:,:) =  getvar(cf_mm, 'glamu', 1,npiglo,npjglo)
+
+   gphiv(:,:) = getvar(cf_mm, 'gphiv', 1,npiglo,npjglo)
+   gphiu(:,:) = getvar(cf_mm, 'gphiu', 1,npiglo,npjglo)
+
+   gdepw(:) = getvare3(cf_mm, 'gdepw_1d',npk)
+   gdept(:) = getvare3(cf_mm, 'gdept_1d',npk)
+
+
+
+
+   DO WHILE ( lcontinue )
+
+      OPEN(numin, FILE=TRIM(cf_sections), status='old')
+      READ(numin,'(a)') csection
+      IF (TRIM(csection) == 'EOF' ) THEN
+         CLOSE(numin)
+         lcontinue = .FALSE.
+         EXIT
+      END IF
+
+      IF ( .NOT. lcontinue ) EXIT
+
+      READ(numin,*) ii0, ii1, ij0, ij1
+      WRITE(*,'(" *** Section = ",a," (",i4.4,", "i4.4,", "i4.4,", "i4.4,") ***")') TRIM(csection), ii0, ii1, ij0, ij1
+      !PRINT*, ' =>', ii0, ii1, ij0, ij1
+
+      !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
+
+      ! Defaults:
+      c1 = cref1           ; c2 = cref2
+      ref_temp = ref_temp0 ; ref_sali = ref_sali0
+      
+      ! Should they be modified:
+      READ(numin,'(a)') ctest
+      IF (ctest(1:14) == 'ref_temp_sali:' ) THEN
+         c0 = TRIM(ctest(14+2:))
+         ispace = SCAN(TRIM(c0),' ')
+         c1 = TRIM((c0(1:ispace-1)))
+         c2 = TRIM((c0(ispace+1:)))
+         READ(c1,*) ref_temp
+         READ(c2,*) ref_sali
+      ELSE
+         BACKSPACE(numin)
+      END IF
+      
+      PRINT *, '  => reference temperature and salinity:', REAL(ref_temp,4), REAL(ref_sali,4)
+
+
+      ! get e3u, e3v  at all levels
+      CALL GETVAR_3D(idf_0, idv_0, cf_mm, 'e3v_0', 0, 0, E3V_3D)
+      idf_0 = 0. ; idv_0 = 0.
+      CALL GETVAR_3D(idf_0, idv_0, cf_mm, 'e3u_0', 0, 0, E3U_3D)
+
+
+
+
+
+
+
+      DO jt = 1, nt !lolo
+         !! -------------
+         
+         PRINT *, ' * [cdftransportiz] jt = ', jt, '  (', TRIM(csection),')'
+
+         !! Reading 3D fields at time jt...
+         CALL GETVAR_3D(idf_u, idv_u,  cf_u, trim(cv_u), nt, jt, U_3D)
+         CALL GETVAR_3D(idf_v, idv_v,  cf_v, trim(cv_v), nt, jt, V_3D)
+
+         IF ( leiv ) THEN
+            CALL GETVAR_3D(idf_ueiv, idv_ueiv,  cf_u, trim(cv_ueiv), nt, jt, UEIV_3D)
+            CALL GETVAR_3D(idf_veiv, idv_veiv,  cf_v, trim(cv_veiv), nt, jt, VEIV_3D)
+         END IF
+
+
+
+         CALL GETVAR_3D(idf_ut, idv_ut, cf_vt, 'vozout', nt, jt, UT_3D)
+         CALL GETVAR_3D(idf_vt, idv_vt, cf_vt, 'vomevt', nt, jt, VT_3D)
+         CALL GETVAR_3D(idf_us, idv_us, cf_vt, 'vozous', nt, jt, US_3D)
+         CALL GETVAR_3D(idf_vs, idv_vs, cf_vt, 'vomevs', nt, jt, VS_3D)
+
+
+
+         ! look for nearest level to imeter
+         ik = 1
+         ilev0(1)      = 1
+         ilev1(nclass) = npk-1
+
+         DO jk = 1, nclass -1
+            DO WHILE ( gdepw(ik)  < imeter(jk) )
+               ik = ik +1
+            END DO
+
+            rd1= ABS(gdepw(ik-1) - imeter(jk) )
+            rd2= ABS(gdepw(ik) - imeter(jk) )
+            IF ( rd2 < rd1 ) THEN
+               ilev1(jk) = ik -1  ! t-levels
+               ilev0(jk+1) = ik
+            ELSE
+               ilev1(jk) = ik -2  ! t-levels
+               ilev0(jk+1) = ik -1
+            END IF
+         END DO
+
+
+
+         !! compute the transport
+         ztrpu (:,:,:)= 0
+         ztrpv (:,:,:)= 0
+
+         ztrput(:,:,:)= 0
+         ztrpvt(:,:,:)= 0
+
+         ztrpus(:,:,:)= 0
+         ztrpvs(:,:,:)= 0
+
+         DO jc = 1, nclass
+
+            DO jk = ilev0(jc),ilev1(jc)
+
+               ! Get velocities, temperature and salinity fluxes at jk
+               zu (:,:) =  U_3D(:,:,jk)
+               zv (:,:) =  V_3D(:,:,jk)
+               IF ( leiv ) THEN
+                  zu(:,:) = zu(:,:) + UEIV_3D(:,:,jk)
+                  zv(:,:) = zv(:,:) + VEIV_3D(:,:,jk)
+               END IF
+
+               zut(:,:) = UT_3D(:,:,jk)
+               zvt(:,:) = VT_3D(:,:,jk)
+               zus(:,:) = US_3D(:,:,jk)
+               zvs(:,:) = VS_3D(:,:,jk)
+
+               e3v(:,:) = E3V_3D(:,:,jk)
+               e3u(:,:) = E3U_3D(:,:,jk)
+
+               zwku (:,:) = zu (:,:)*e2u(:,:)*e3u(:,:)
+               zwkv (:,:) = zv (:,:)*e1v(:,:)*e3v(:,:)
+               zwkut(:,:) = zut(:,:)*e2u(:,:)*e3u(:,:)
+               zwkvt(:,:) = zvt(:,:)*e1v(:,:)*e3v(:,:)
+               zwkus(:,:) = zus(:,:)*e2u(:,:)*e3u(:,:)
+               zwkvs(:,:) = zvs(:,:)*e1v(:,:)*e3v(:,:)
+
+               ! integrates vertically
+               ztrpu (:,:,jc) = ztrpu (:,:,jc) + zwku (:,:)
+               ztrpv (:,:,jc) = ztrpv (:,:,jc) + zwkv (:,:)
+
+               ztrput(:,:,jc) = ztrput(:,:,jc) + zwkut(:,:) * rau0*rcp
+               ztrpvt(:,:,jc) = ztrpvt(:,:,jc) + zwkvt(:,:) * rau0*rcp
+
+               ztrpus(:,:,jc) = ztrpus(:,:,jc) + zwkus(:,:)
+               ztrpvs(:,:,jc) = ztrpvs(:,:,jc) + zwkvs(:,:)
+
+            END DO  ! loop to next level
+         END DO    ! next class
+
+
+
+         IF (jt == 1) THEN
+
+            IF ( nclass > 3 ) THEN
+               PRINT *, ' ERROR => cdftransportiz.f90 only supports 2 depths currently!!!'
+            END IF
+
+
+            !! Find the broken line between P1 (ii0,ij0) and P2 (ii1, ij1)
+            !! ---------------------------------------------------------------
+            ! ... Initialization
+            !i0=ii0; j0=ij0; i1=ii1;  j1=ij1
+            rxi1=ii1;  ryj1=ij1; rxi0=ii0; ryj0=ij0
+
+            ! .. Compute equation:  ryj = aj rxi + bj
+            IF ( (rxi1 -rxi0) /=  0 ) THEN
+               aj = (ryj1 - ryj0 ) / (rxi1 -rxi0)
+               bj = ryj0 - aj * rxi0
+            ELSE
+               aj=10000.
+               bj=0.
+            END IF
+
+            ! .. Compute equation:  rxi = ai ryj + bi
+            IF ( (ryj1 -ryj0) /=  0 ) THEN
+               ai = (rxi1 - rxi0 ) / ( ryj1 -ryj0 )
+               bi = rxi0 - ai * ryj0
+            ELSE
+               ai=10000.
+               bi=0.
+            END IF
+
+            ! ..  Compute the integer pathway:
+            n=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 and remember it has been swapped
+               IF (ii1 <  ii0 ) THEN
+                  i  = ii0 ; j  = ij0
+                  ii0 = ii1 ; ij0 = ij1
+                  ii1 = i  ; ij1 = j
+               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 j point on the line crossing at i
+               DO i=ii0,ii1
+                  n=n+1
+                  IF (n > jpseg) STOP 'n > jpseg !'
+                  j=NINT(aj*i + bj )
+                  yypt(n) = CMPLX(i,j)
+               END DO
+            ELSE
+
+               ! ... Here, the best line is x(y)
+               ! ... If ij1 < ij0 swap points and remember it has been swapped
+               IF (ij1 <  ij0 ) THEN
+                  i  = ii0 ; j  = ij0
+                  ii0 = ii1 ; ij0 = ij1
+                  ii1 = i  ; ij1 = j
+               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 i point on the line crossing at j
+               DO j=ij0,ij1
+                  n=n+1
+                  IF (n > jpseg) STOP 'n>jpseg !'
+                  i=NINT(ai*j + bi)
+                  yypt(n) = CMPLX(i,j)
+               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 k=2,n
+               ! .. distance between 2 neighbour points
+               d=ABS(yypt(k)-yypt(k-1))
+               ! .. intermediate points required if d > 1
+               IF ( d > 1 ) THEN
+                  CALL interm_pt(yypt,k,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(k))
+               ryy(nn)=IMAG(yypt(k))
+            END DO
+
+            IF ( l_save_broken_lines ) THEN
+               !! LOLO: We want to save the Broken line in an ascci file for further use:
+               WRITE(cf_broken_line,'("broken_line_",a,".dat")') trim(csection)
+               OPEN(UNIT=19, FILE=trim(cf_broken_line), FORM='FORMATTED', RECL=256, STATUS='unknown')
+               PRINT *, 'Saving broken line into file ', trim(cf_broken_line)
+               WRITE(19,*)'#       ji          jj'
+               DO jseg = 1, nn
+                  ii0=rxx(jseg)
+                  ij0=ryy(jseg)
+                  WRITE(19,*) ii0, ij0
+               END DO
+               CLOSE(19)
+               PRINT *, ''
+            END IF
+
+         END IF !* IF ( jt == 1 )
+
+
+
+
+
+         DO jc=1,nclass
+
+            voltrpsum = 0.
+            heatrpsum = 0.
+            saltrpsum = 0.
+            frwtrpsum = 0.
+
+            DO jseg = 1, nn-1
+               ii0=rxx(jseg)
+               ij0=ryy(jseg)
+               IF ( rxx(jseg) ==  rxx(jseg+1) ) THEN
+                  gla(jseg)=glamu(ii0,ij0+ijst)   ; gphi(jseg)=gphiu(ii0,ij0+ijst)
+                  voltrp(jseg)= ztrpu (ii0,ij0+ijst,jc)*norm_u
+                  heatrp(jseg)= ztrput(ii0,ij0+ijst,jc)*norm_u
+                  saltrp(jseg)= ztrpus(ii0,ij0+ijst,jc)*norm_u
+               ELSE IF ( ryy(jseg) == ryy(jseg+1) ) THEN
+                  gla(jseg)=glamv(ii0+iist,ij0)  ;  gphi(jseg)=gphiv(ii0+iist,ij0)
+                  voltrp(jseg)=ztrpv (ii0+iist,ij0,jc)*norm_v
+                  heatrp(jseg)=ztrpvt(ii0+iist,ij0,jc)*norm_v
+                  saltrp(jseg)=ztrpvs(ii0+iist,ij0,jc)*norm_v
+               ELSE
+                  PRINT *,' ERROR :',  rxx(jseg),ryy(jseg),rxx(jseg+1),ryy(jseg+1)
+               END IF
+               voltrpsum = voltrpsum+voltrp(jseg)
+               heatrpsum = heatrpsum+heatrp(jseg)
+               saltrpsum = saltrpsum+saltrp(jseg)
+            END DO   ! next segment
+
+            frwtrpsum = voltrpsum - saltrpsum/ref_sali               ! only valid if saltrpsum was calculated with a ref salinity of 0.!
+            heatrpsum = heatrpsum - rau0*rcp*ref_temp*voltrpsum
+            saltrpsum = saltrpsum -          ref_sali*voltrpsum
+
+
+            X_trsp(:,jt,jc) = (/ REAL(voltrpsum/1.e6,4), REAL(heatrpsum/1.e15,4), REAL(saltrpsum/1.e6,4), REAL(frwtrpsum/1.e6,4) /)
+
+
+         END DO ! next class
+
+      END DO ! loop on jt
+
+
+
+
+
+      !! Time to create or append X_trsp into the netcdf file for current section
+      !! -----------------------------------------------------
+
+      WRITE(cf_out, '(a,"/transport_sect_",a,".nc")') trim(cd_out), trim(csection)
+      IF ( leiv ) WRITE(cf_out, '(a,"/transport_sect_",a,"_eiv.nc")') trim(cd_out), trim(csection)
+
+      id_volu = 0 ; id_heat = 0 ; id_salt = 0 ; id_frwt = 0
+
+      !! LOLO netcdf
+      INQUIRE( FILE=cf_out, EXIST=lfncout )
+
+
+      IF ( .NOT. lfncout ) THEN
+
+         !! Creating file
+         PRINT *, ' Creating file '//trim(cf_out)//' !!!'
+         ierr = NF90_CREATE(cf_out, NF90_CLOBBER, idf_out)
+         ierr = NF90_DEF_DIM(idf_out, 'time', NF90_UNLIMITED, idd_t)
+         ierr = NF90_DEF_VAR(idf_out, 'time', NF90_DOUBLE,    idd_t, idv_time)
+
+
+         ierr = NF90_DEF_VAR(idf_out, 'trsp_volu', NF90_FLOAT, (/idd_t/), id_volu(0))
+         ierr = NF90_DEF_VAR(idf_out, 'trsp_heat', NF90_FLOAT, (/idd_t/), id_heat(0))
+         ierr = NF90_DEF_VAR(idf_out, 'trsp_salt', NF90_FLOAT, (/idd_t/), id_salt(0))
+         ierr = NF90_DEF_VAR(idf_out, 'trsp_frwt', NF90_FLOAT, (/idd_t/), id_frwt(0))
+
+         ierr = NF90_PUT_ATT(idf_out, id_volu(0), 'long_name', 'TOTAL: Transport of volume')
+         ierr = NF90_PUT_ATT(idf_out, id_heat(0), 'long_name', 'TOTAL: Transport of heat')
+         ierr = NF90_PUT_ATT(idf_out, id_salt(0), 'long_name', 'TOTAL: Transport of salt')
+         ierr = NF90_PUT_ATT(idf_out, id_frwt(0), 'long_name', 'TOTAL: Transport of liquid freshwater')
+
+         ierr = NF90_PUT_ATT(idf_out, id_volu(0), 'units', 'Sv')
+         ierr = NF90_PUT_ATT(idf_out, id_heat(0), 'units', 'PW')
+         ierr = NF90_PUT_ATT(idf_out, id_salt(0), 'units', 'kt/s')
+         ierr = NF90_PUT_ATT(idf_out, id_frwt(0), 'units', 'Sv')
+
+         ierr = NF90_PUT_ATT(idf_out, id_heat(0), 'Tref', c1)
+         ierr = NF90_PUT_ATT(idf_out, id_salt(0), 'Sref', c2)
+         ierr = NF90_PUT_ATT(idf_out, id_frwt(0), 'Sref', c2)
+         
+         IF ( nclass > 1 ) THEN
+            DO jc = 1, nclass
+               WRITE(cdum,'("_",i2.2)') jc ! suffix for variable_name
+               ierr = NF90_DEF_VAR(idf_out, 'trsp_volu'//trim(cdum), NF90_FLOAT, (/idd_t/), id_volu(jc))
+               ierr = NF90_DEF_VAR(idf_out, 'trsp_heat'//trim(cdum), NF90_FLOAT, (/idd_t/), id_heat(jc))
+               ierr = NF90_DEF_VAR(idf_out, 'trsp_salt'//trim(cdum), NF90_FLOAT, (/idd_t/), id_salt(jc))
+               ierr = NF90_DEF_VAR(idf_out, 'trsp_frwt'//trim(cdum), NF90_FLOAT, (/idd_t/), id_frwt(jc))
+
+               WRITE(cdum,'(f7.2,"-",f7.2,"m  (t-points)")') gdept(ilev0(jc)), gdept(ilev1(jc))
+
+               ierr = NF90_PUT_ATT(idf_out, id_volu(jc), 'long_name', 'Transport of volume, '//trim(cdum))
+               ierr = NF90_PUT_ATT(idf_out, id_heat(jc), 'long_name', 'Transport of heat, '//trim(cdum))
+               ierr = NF90_PUT_ATT(idf_out, id_salt(jc), 'long_name', 'Transport of salt, '//trim(cdum))
+               ierr = NF90_PUT_ATT(idf_out, id_frwt(jc), 'long_name', 'Transport of liquid freshwater, '//trim(cdum))
+
+               ierr = NF90_PUT_ATT(idf_out, id_volu(jc), 'units', 'Sv')
+               ierr = NF90_PUT_ATT(idf_out, id_heat(jc), 'units', 'PW')
+               ierr = NF90_PUT_ATT(idf_out, id_salt(jc), 'units', 'kt/s')
+               ierr = NF90_PUT_ATT(idf_out, id_frwt(jc), 'units', 'Sv')
+
+               ierr = NF90_PUT_ATT(idf_out, id_heat(jc), 'Tref', c1)
+               ierr = NF90_PUT_ATT(idf_out, id_salt(jc), 'Sref', c2)
+               ierr = NF90_PUT_ATT(idf_out, id_frwt(jc), 'Sref', c2)
+
+            END DO
+         END IF
+
+         ierr = NF90_PUT_ATT(idf_out, NF90_GLOBAL, &
+            &   'Info1', 'Reference temperature for heat transport is '//TRIM(c1)//' deg.C')
+         ierr = NF90_PUT_ATT(idf_out, NF90_GLOBAL, &
+            &   'Info2', 'Reference salinity for salt and freshwater transports is '//TRIM(c2)//' PSU')
+         ierr = NF90_PUT_ATT(idf_out, NF90_GLOBAL, 'About', &
+            &   'Created by BaraKuda (cdftransportiz.f90) => https://github.com/brodeau/barakuda')
+
+         ierr = NF90_ENDDEF(idf_out)
+         jt_pos = 0
+
+      ELSE
+
+         !! Opening already existing file
+         ierr = NF90_OPEN  (cf_out, NF90_WRITE,   idf_out)
+
+         !! Need IDs of variables to append... NF90_INQ_VARID
+         ierr = NF90_INQ_VARID(idf_out, 'trsp_volu', id_volu(0))
+         ierr = NF90_INQ_VARID(idf_out, 'trsp_heat', id_heat(0))
+         ierr = NF90_INQ_VARID(idf_out, 'trsp_salt', id_salt(0))
+         ierr = NF90_INQ_VARID(idf_out, 'trsp_frwt', id_frwt(0))
+
+         IF ( nclass > 1 ) THEN
+            DO jc = 1, nclass
+               WRITE(cdum,'("_",i2.2)') jc ! suffix for variable_name
+               ierr = NF90_INQ_VARID(idf_out, 'trsp_volu'//trim(cdum), id_volu(jc))
+               ierr = NF90_INQ_VARID(idf_out, 'trsp_heat'//trim(cdum), id_heat(jc))
+               ierr = NF90_INQ_VARID(idf_out, 'trsp_salt'//trim(cdum), id_salt(jc))
+               ierr = NF90_INQ_VARID(idf_out, 'trsp_frwt'//trim(cdum), id_frwt(jc))
+            END DO
+         END IF
+
+         ! Get ID of unlimited dimension
+         ierr = NF90_INQUIRE(idf_out, unlimitedDimId = idv_time)
+
+         ! Need to know jt_pos, record number of the last time record writen in the file
+         ierr = NF90_INQUIRE_DIMENSION(idf_out, idv_time, name=cv_dum, len=jt_pos)
+
+      END IF
+
+      WRITE(*,'("Going to write record ",i4.4," to ",i4.4," into ",a)') jt_pos+1, jt_pos+nt, trim(cf_out)
+
+      DO jt = 1, nt
+
+         ! Writing record jt for time vector and 1d fields:
+         ierr = NF90_PUT_VAR( idf_out, idv_time, (/ryear+1./12.*(REAL(jt)-1.+0.5)/), start=(/jt_pos+jt/), count=(/1/) )
+
+         IF ( nclass == 1 ) THEN
+            !! Default variable is the only one present (index = 1) :
+            ierr = NF90_PUT_VAR(idf_out, id_volu(0), (/ X_trsp(1,jt,1) /), start=(/jt_pos+jt/), count=(/1/))
+            ierr = NF90_PUT_VAR(idf_out, id_heat(0), (/ X_trsp(2,jt,1) /), start=(/jt_pos+jt/), count=(/1/))
+            ierr = NF90_PUT_VAR(idf_out, id_salt(0), (/ X_trsp(3,jt,1) /), start=(/jt_pos+jt/), count=(/1/))
+            ierr = NF90_PUT_VAR(idf_out, id_frwt(0), (/ X_trsp(4,jt,1) /), start=(/jt_pos+jt/), count=(/1/))
+
+         ELSE
+
+            !! Default variable is the sum:
+            ierr = NF90_PUT_VAR(idf_out, id_volu(0), (/ SUM(X_trsp(1,jt,:)) /), start=(/jt_pos+jt/), count=(/1/))
+            ierr = NF90_PUT_VAR(idf_out, id_heat(0), (/ SUM(X_trsp(2,jt,:)) /), start=(/jt_pos+jt/), count=(/1/))
+            ierr = NF90_PUT_VAR(idf_out, id_salt(0), (/ SUM(X_trsp(3,jt,:)) /), start=(/jt_pos+jt/), count=(/1/))
+            ierr = NF90_PUT_VAR(idf_out, id_frwt(0), (/ SUM(X_trsp(4,jt,:)) /), start=(/jt_pos+jt/), count=(/1/))
+
+            DO jc = 1, nclass
+               ierr = NF90_PUT_VAR(idf_out, id_volu(jc), (/ X_trsp(1,jt,jc) /), start=(/jt_pos+jt/), count=(/1/))
+               ierr = NF90_PUT_VAR(idf_out, id_heat(jc), (/ X_trsp(2,jt,jc) /), start=(/jt_pos+jt/), count=(/1/))
+               ierr = NF90_PUT_VAR(idf_out, id_salt(jc), (/ X_trsp(3,jt,jc) /), start=(/jt_pos+jt/), count=(/1/))
+               ierr = NF90_PUT_VAR(idf_out, id_frwt(jc), (/ X_trsp(4,jt,jc) /), start=(/jt_pos+jt/), count=(/1/))
+            END DO
+         END IF
+
+      END DO
+
+      ierr = NF90_CLOSE(idf_out)
+
+      PRINT *, ''
+
+   END DO ! loop on sections...
+
+   DEALLOCATE( X_trsp ) !lolo
+
+
+CONTAINS
+
+
+   SUBROUTINE interm_pt (ydpt,k,pai,pbi,paj,pbj,ydpti)
+      !! -----------------------------------------------------
+      !!           SUBROUTINE INTERM_PT
+      !!           ********************
+      !!
+      !!   PURPOSE:
+      !!   --------
+      !!     Find the best intermediate points on a pathway.
+      !!
+      !!    ARGUMENTS:
+      !!    ----------
+      !!      ydpt : complex vector of the positions of the nearest points
+      !!         k : 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
+      !!
+      !!    AUTHOR:
+      !!    -------
+      !!      19/07/1999 : Jean-Marc MOLINES
+      !!      14/01/2005 : J M M in F90
+      !!
+      !!--------------------------------------------------------------
+      !!
+      !! 0. Declarations:
+      !! ----------------
+      IMPLICIT NONE
+      COMPLEX, INTENT(in) :: ydpt(*)
+      COMPLEX, INTENT(out) :: ydpti
+      REAL(4), INTENT(IN) ::  pai,pbi,paj,pbj
+      INTEGER ,INTENT(in) :: k
+      ! ... local
+      COMPLEX :: ylptmp1, ylptmp2
+      REAL(4) ::  za0,zb0,za1,zb1,zd1,zd2
+      REAL(4) ::  zxm,zym
+      REAL(4) ::  zxp,zyp
+      !!
+      !! 1. Compute intermediate points
+      !! ------------------------------
+      !
+      ! ... Determines whether we use y(x) or x(y):
+      IF (ABS(paj) <=  1) THEN
+         ! ..... y(x)
+         ! ... possible intermediate points:
+         ylptmp1=ydpt(k-1)+(1.,0.)
+         ylptmp2=ydpt(k-1)+CMPLX(0.,SIGN(1.,paj))
+         !
+         ! ... M is the candidate point:
+         zxm=REAL(ylptmp1)
+         zym=IMAG(ylptmp1)
+         za0=paj
+         zb0=pbj
+         !
+         za1=-1./za0
+         zb1=zym - za1*zxm
+         ! ... P is the projection of M on the strait line
+         zxp=-(zb1-zb0)/(za1-za0)
+         zyp=za0*zxp + zb0
+         ! ... zd1 is the distance MP
+         zd1=(zxm-zxp)*(zxm-zxp) + (zym-zyp)*(zym-zyp)
+         !
+         ! ... M is the candidate point:
+         zxm=REAL(ylptmp2)
+         zym=IMAG(ylptmp2)
+         za1=-1./za0
+         zb1=zym - za1*zxm
+         ! ... P is the projection of M on the strait line
+         zxp=-(zb1-zb0)/(za1-za0)
+         zyp=za0*zxp + zb0
+         ! ... zd2 is the distance MP
+         zd2=(zxm-zxp)*(zxm-zxp) + (zym-zyp)*(zym-zyp)
+         ! ... chose the smallest (zd1,zd2)
+         IF (zd2 <=  zd1) THEN
+            ydpti=ylptmp2
+         ELSE
+            ydpti=ylptmp1
+         END IF
+         !
+      ELSE
+         !
+         ! ... x(y)
+         ylptmp1=ydpt(k-1)+CMPLX(SIGN(1.,pai),0.)
+         ylptmp2=ydpt(k-1)+(0.,1.)
+         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 cdftransportiz

+ 250 - 0
cdftools_light/src/cdfvT.f90

@@ -0,0 +1,250 @@
+PROGRAM cdfvT
+
+
+  !!-------------------------------------------------------------------
+  !!                ***  PROGRAM cdfvT  ***
+  !!
+  !!  **  Purpose:
+  !!
+  !!  **  Method: Try to avoid 3 d arrays
+  !!              Assume that all input files have the same number of time frames
+  !!
+  !! history :
+  !!   L. Brodeau , 2014 for BaraKuda !!
+  !!
+  !!   Original : J.M. Molines (Nov 2004 ) for ORCA025
+  !!              J.M. Molines (apr 2005 ) : use of modules
+  !!              J.M. Molines (Feb. 2010 ): handle multiframes input files.
+  !!-------------------------------------------------------------------
+  !!  $Rev: 317 $
+  !!  $Date: 2010-05-17 14:47:12 +0200 (Mon, 17 May 2010) $
+  !!  $Id: cdfvT.f90 317 2010-05-17 12:47:12Z molines $
+  !!--------------------------------------------------------------
+
+
+
+  USE cdfio
+  USE io_ezcdf
+
+
+  !! * Local variables
+  IMPLICIT NONE
+  INTEGER   :: ji,jj,jk,jt,jkk                !: dummy loop index
+  INTEGER   :: ierr                                !: working integer
+  INTEGER   :: narg, iargc
+  INTEGER   :: npiglo,npjglo, npk, nt              !: size of the domain
+
+  INTEGER, DIMENSION(4) ::  ipk, id_varout
+
+
+  REAL(KIND=4) , DIMENSION (:),   ALLOCATABLE :: vtime ! lolo
+  REAL(KIND=4) , DIMENSION (:),   ALLOCATABLE :: vdepth ! lolo
+  REAL(KIND=4) , DIMENSION (:,:), ALLOCATABLE :: xlon, xlat  ! lolo
+  REAL(KIND=4) , DIMENSION (:,:,:), ALLOCATABLE :: T_3D, S_3D, U_3D, V_3D, UEIV_3D, VEIV_3D, X_3D_u, X_3D_v   !: lolo
+  INTEGER(2)   , DIMENSION (:,:,:), ALLOCATABLE :: mask_3d
+
+  REAL(KIND=8) , DIMENSION (:,:,:), ALLOCATABLE :: zcumulut, zcumulus  !: Arrays for cumulated values
+  REAL(KIND=8) , DIMENSION (:,:,:), ALLOCATABLE :: zcumulvt, zcumulvs  !: Arrays for cumulated values
+
+  CHARACTER(LEN=256) :: cf_mm='mesh_mask.nc'
+
+  CHARACTER(LEN=256) :: cf_t,cf_u,cf_v , cf_out, conf_tag , ctim !:
+  TYPE (variable), DIMENSION(4)     :: typvar     !: structure for attributes
+  LOGICAL :: lexist                               !: to inquire existence of files
+
+  INTEGER    :: istatus
+
+  CHARACTER(LEN=64) :: cv_t, cv_s, cv_u, cv_v, cv_ueiv, cv_veiv
+
+  INTEGER :: idf_t=0, idv_t=0, idf_s=0, idv_s=0, &
+       &     idf_u=0, idv_u=0, idf_v=0, idv_v=0, &
+       &     idf_ueiv=0, idv_ueiv=0, idf_veiv=0, idv_veiv=0
+
+  INTEGER :: idf_vt=0, idv_vt=0, idv_vs=0, idv_ut=0, idv_us=0, idf_0=0, idv_0=0
+
+
+
+  CHARACTER(LEN=100) :: cv_depth = 'deptht'
+
+  LOGICAL :: leiv = .FALSE.
+
+
+  !!  Read command line
+  narg= iargc()
+  IF ( (narg < 5).OR.(narg > 7).OR.(narg == 6) ) THEN
+     PRINT *,' Usage : cdfvT <CONF_TAG> <name T> <name S> <name U> <name V> (<name Ueiv> <name Veiv>)'
+     PRINT *,'    => files are: <CONF_TAG>_grid_T.nc <CONF_TAG>_grid_U.nc <CONF_TAG>_grid_V.nc'     
+     PRINT *,' Files mesh_mask.nc must be in te current directory'
+     STOP
+  ENDIF
+
+  CALL getarg (1, conf_tag)
+  CALL getarg (2, cv_t)
+  CALL getarg (3, cv_s)
+  CALL getarg (4, cv_u)
+  CALL getarg (5, cv_v)
+
+  PRINT *, ' Will compute VT using '//trim(cv_u)//' and '//trim(cv_v)
+
+  IF (narg == 7) THEN
+     leiv = .TRUE.     
+     CALL getarg (6, cv_ueiv)
+     CALL getarg (7, cv_veiv)
+     IF ( (trim(cv_ueiv) == '0').AND.(trim(cv_veiv) == '0') )   leiv = .FALSE.
+  END IF
+  
+  
+  IF ( leiv) &
+       & PRINT *, ' and taking eddy-induced velocity into account using '//trim(cv_ueiv)//' and '//trim(cv_veiv)
+
+  !! Initialisation from 1st file (all file are assume to have the same geometry)
+
+
+  WRITE(cf_out,'(a,"_VT.nc")') trim(conf_tag)
+  
+  WRITE(cf_t,'(a,"_grid_T.nc")') trim(conf_tag)
+  INQUIRE(FILE=cf_t,EXIST=lexist)
+  IF ( .NOT. lexist ) THEN
+     WRITE(cf_t,'(a,"_grid_T.nc4")') trim(conf_tag)
+     INQUIRE(FILE=cf_t,EXIST=lexist)
+     IF ( .NOT. lexist ) THEN
+        PRINT *,' ERROR : missing grid_T or even gridT file '
+        STOP
+     ENDIF
+  ENDIF
+
+  PRINT *,TRIM(cf_t)
+  npiglo= getdim (cf_t,'x')
+  npjglo= getdim (cf_t,'y')
+  npk   = getdim (cf_t,'depth')
+
+  ctim = 'none'
+  nt    = getdim (cf_t,'time',cdtrue=ctim,kstatus=istatus) !LB
+
+
+  !LB:
+  IF (nt == 0) THEN
+     PRINT *, 'nt=0, assume 1' ; nt = 1
+  END IF
+  !LB.
+
+
+  PRINT *, 'npiglo=', npiglo
+  PRINT *, 'npjglo=', npjglo
+  PRINT *, 'npk   =', npk
+
+  ALLOCATE( vtime(nt), vdepth(npk), xlon(npiglo,npjglo), xlat(npiglo,npjglo) )
+
+  ALLOCATE( T_3D(npiglo,npjglo,npk), S_3D(npiglo,npjglo,npk), U_3D(npiglo,npjglo,npk), V_3D(npiglo,npjglo,npk) )
+  ALLOCATE( X_3D_u(npiglo,npjglo,npk), X_3D_v(npiglo,npjglo,npk) )
+  ALLOCATE( mask_3d(npiglo,npjglo,npk) )
+
+  IF ( leiv ) ALLOCATE( UEIV_3D(npiglo,npjglo,npk), VEIV_3D(npiglo,npjglo,npk) )
+
+  ALLOCATE( zcumulut(npiglo,npjglo,npk), zcumulus(npiglo,npjglo,npk) )
+  ALLOCATE( zcumulvt(npiglo,npjglo,npk), zcumulvs(npiglo,npjglo,npk) )
+
+
+
+  
+  vtime  = getvar1d(cf_t, trim(ctim), nt) !LB
+  vdepth = getvar1d(cf_t, trim(cv_depth), npk) !LB
+  
+  !LB: Read lon and lat in mesh_mask to avoid problem with files with missing values on "removed land processors":
+  xlon(:,:) = getvar(cf_mm, 'nav_lon', 1,npiglo,npjglo)
+  xlat(:,:) = getvar(cf_mm, 'nav_lat', 1,npiglo,npjglo)
+  
+  CALL GETMASK_3D(cf_mm, 'tmask', mask_3d)
+
+  WRITE(cf_t,'(a,"_grid_T.nc")') trim(conf_tag)
+  INQUIRE(FILE=cf_t,EXIST=lexist)
+  IF ( .NOT. lexist ) THEN
+     WRITE(cf_t,'(a,"_grid_T.nc4")') trim(conf_tag)
+     INQUIRE(FILE=cf_t,EXIST=lexist)
+     IF ( .NOT. lexist ) THEN
+        PRINT *,' ERROR : missing gridT or even grid_T file '
+        STOP
+     ENDIF
+  ENDIF
+
+  ! assume U and V file have same time span ...
+  WRITE(cf_u,'(a,"_grid_U.nc")') trim(conf_tag)
+  INQUIRE(FILE=cf_u,EXIST=lexist)
+  IF ( .NOT. lexist ) THEN
+     WRITE(cf_u,'(a,"_grid_U.nc4")') trim(conf_tag)
+     INQUIRE(FILE=cf_u,EXIST=lexist)
+     IF ( .NOT. lexist ) THEN
+        PRINT *,' ERROR : missing grid_U or even gridU file '
+        STOP
+     ENDIF
+  ENDIF
+
+  WRITE(cf_v,'(a,"_grid_V.nc")') trim(conf_tag)
+  INQUIRE(FILE=cf_v,EXIST=lexist)
+  IF ( .NOT. lexist ) THEN
+     WRITE(cf_v,'(a,"_grid_V.nc4")') trim(conf_tag)
+     INQUIRE(FILE=cf_v,EXIST=lexist)
+     IF ( .NOT. lexist ) THEN
+        PRINT *,' ERROR : missing grid_V or even gridV file '
+        STOP
+     ENDIF
+  ENDIF
+
+
+
+
+
+
+  DO jt=1,nt
+
+     PRINT *, ' * [cdfvT] jt = ', jt
+
+     CALL GETVAR_3D(idf_t, idv_t, cf_t, cv_t, nt, jt, T_3D)
+     CALL GETVAR_3D(idf_s, idv_s, cf_t, cv_s, nt, jt, S_3D)
+     CALL GETVAR_3D(idf_u, idv_u, cf_u, cv_u, nt, jt, U_3D)
+     CALL GETVAR_3D(idf_v, idv_v, cf_v, cv_v, nt, jt, V_3D)     
+     
+     IF ( leiv ) THEN
+        CALL GETVAR_3D(idf_ueiv, idv_ueiv, cf_u, cv_ueiv, nt, jt, UEIV_3D)
+        CALL GETVAR_3D(idf_veiv, idv_veiv, cf_v, cv_veiv, nt, jt, VEIV_3D)
+        U_3D = U_3D + UEIV_3D
+        V_3D = V_3D + VEIV_3D
+     END IF
+
+     !LB: to avoid problem with files with missing values on "removed land processors":
+     T_3D = T_3D*mask_3d
+     S_3D = S_3D*mask_3d
+     U_3D = U_3D*mask_3d
+     V_3D = V_3D*mask_3d
+
+     zcumulut(:,:,:) = 0.d0 ;  zcumulvt(:,:,:) = 0.d0 !; total_time = 0.
+     zcumulus(:,:,:) = 0.d0 ;  zcumulvs(:,:,:) = 0.d0
+
+     ! temperature
+     X_3D_u(1:npiglo-1,:, :) = 0.5 * ( T_3D(1:npiglo-1,:, :) + T_3D(2:npiglo,:, :) )  ! temper at Upoint
+     X_3D_v(:,1:npjglo-1, :) = 0.5 * ( T_3D(:,1:npjglo-1, :) + T_3D(:,2:npjglo, :) )  ! temper at Vpoint
+
+     zcumulut(:,:,:) = X_3D_u(:,:,:) * U_3D(:,:,:)
+     zcumulvt(:,:,:) = X_3D_v(:,:,:) * V_3D(:,:,:)
+
+     ! salinity
+     X_3D_u(1:npiglo-1,:, :) = 0.5 * ( S_3D(1:npiglo-1,:, :) + S_3D(2:npiglo,:, :) )  ! salinity at Upoint
+     X_3D_v(:,1:npjglo-1, :) = 0.5 * ( S_3D(:,1:npjglo-1, :) + S_3D(:,2:npjglo, :) )  ! salinity at Vpoint
+
+     zcumulus(:,:,:) = X_3D_u(:,:,:) * U_3D(:,:,:)
+     zcumulvs(:,:,:) = X_3D_v(:,:,:) * V_3D(:,:,:)
+
+
+     !! Printing record jt:
+     CALL P3D_T_4v(idf_vt, idv_vt, idv_vs, idv_ut, idv_us, nt, jt, xlon, xlat, vdepth, REAL(vtime,8), &
+          &        REAL(zcumulvt,4), REAL(zcumulvs,4), REAL(zcumulut,4), REAL(zcumulus,4),  &
+          &        cf_out, 'nav_lon', 'nav_lat', trim(cv_depth), 'time_counter', &
+          &        'vomevt', 'vomevs', 'vozout', 'vozous', &
+          &        0., 'seconds', 'm')
+     
+
+  END DO ! jt
+
+  PRINT *, '  *** cdfvT => '//trim(cf_out)//' written!'; PRINT *, ''
+
+END PROGRAM cdfvT

+ 178 - 0
cdftools_light/src/cdfw.f90

@@ -0,0 +1,178 @@
+PROGRAM cdfw
+  !!---------------------------------------------------------------------------
+  !!         ***  PROGRAM  cdfw  ***
+  !!
+  !!  **  Purpose: Compute the 3D w 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 code )
+  !!                PARTIAL STEPS 
+  !!
+  !! history :
+  !!   Original :  J.M. Molines (June 2005)
+  !!---------------------------------------------------------------------
+  !!  $Rev: 256 $
+  !!  $Date: 2009-07-21 17:49:27 +0200 (Tue, 21 Jul 2009) $
+  !!  $Id: cdfw.f90 256 2009-07-21 15:49:27Z molines $
+  !!--------------------------------------------------------------
+  !! * Modules used
+  USE cdfio
+
+  !! * Local variables
+  IMPLICIT NONE
+  INTEGER :: ji,jj,jk,jt                              !: dummy loop index
+  INTEGER :: npiglo, npjglo, npk, nt                  !: size of the domain
+  INTEGER :: narg, iargc, ncout, ierr, istatus              !: 
+  INTEGER, DIMENSION(1) ::  ipk, id_varout         ! 
+  INTEGER               :: itop = 1 , ibot = 2 , itmp
+
+  REAL(kind=8), DIMENSION(:,:), ALLOCATABLE  :: e1v, e2u, e1t, e2t  !: metrics
+  REAL(kind=8), DIMENSION(:,:), ALLOCATABLE  :: e3u,e3v,e3t         !:   ""
+  REAL(kind=4), DIMENSION(:,:), ALLOCATABLE  :: glamt, gphit        !: longitude latitude
+  REAL(kind=4), DIMENSION(:)  , ALLOCATABLE  :: gdepw               !: 
+  REAL(kind=4), DIMENSION(:,:), ALLOCATABLE  :: un, vn
+  REAL(kind=8), DIMENSION(:,:), ALLOCATABLE  ::  hdivn
+  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  ::  tim !LB
+
+  CHARACTER(LEN=256) :: cfilu, cfilv, ctim
+  CHARACTER(LEN=256) :: chgr='mesh_hgr.nc', czgr='mesh_zgr.nc', cfileout='w.nc'
+  CHARACTER(LEN=256) :: cvaru='vozocrtx', cvarv='vomecrty', cvarw='vovecrtz'
+
+  TYPE(variable), DIMENSION(1)      :: typvar     !: structure for attributes
+
+  !!
+  narg = iargc()
+  IF ( narg < 2 ) THEN
+     PRINT *,' USAGE : cdfw fileU fileV [varU varV] '
+     PRINT *,'        version PARTIAL STEPS '
+     PRINT *,'        Produce a cdf file w.nc with vovecrtz  variable'
+     PRINT *,'        Need mesh_hgr.nc mesh_zgr.nc'
+     PRINT *,'        If no varU and varV variables given, assume vozocrtx, vomecrty'
+     STOP
+  ENDIF
+
+  CALL getarg(1, cfilu)
+  CALL getarg(2, cfilv)
+  IF ( narg >2 ) THEN
+     CALL getarg(3, cvaru)
+     CALL getarg(4, cvarv)
+  ENDIF
+
+  npiglo = getdim(cfilu,'x')
+  npjglo = getdim(cfilu,'y')
+  npk    = getdim(cfilu,'depth')
+
+  ctim = 'none'
+  nt    = getdim (cfilu,'time',cdtrue=ctim,kstatus=istatus) !LB
+
+  PRINT *, 'nk     =',npk  !LB
+  PRINT *, 'nt     =',nt  !LB
+
+  !LB:
+  IF (nt == 0) THEN
+     PRINT *, 'nt=0, assume 1' ; nt = 1
+  END IF
+  !LB.
+  
+
+
+  ! define new variables for output ( must update att.txt)
+  typvar(1)%name= TRIM(cvarw)
+  typvar(1)%units='m/s'
+  typvar(1)%missing_value=0.
+  typvar(1)%valid_min= -1.
+  typvar(1)%valid_max= 1.
+  typvar(1)%long_name='Vertical_Velocity'
+  typvar(1)%short_name=TRIM(cvarw)
+  typvar(1)%online_operation='N/A'
+  typvar(1)%axis='TZYX'
+
+  ipk(1) = npk             !  3D
+
+  ! 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) , gdepw(npk) )
+  ALLOCATE ( tim(nt) ) !LB
+
+  ! Read the metrics from the mesh_hgr file
+  e2u=  getvar(chgr, 'e2u', 1,npiglo,npjglo)
+  e1v=  getvar(chgr, 'e1v', 1,npiglo,npjglo)
+  e1t=  getvar(chgr, 'e1t', 1,npiglo,npjglo)
+  e2t=  getvar(chgr, 'e2t', 1,npiglo,npjglo)
+
+  ! and the coordinates   from the mesh_hgr file
+  glamt = getvar(chgr, 'glamt', 1,npiglo,npjglo)
+  gphit = getvar(chgr, '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(czgr,'gdepw',npk)
+
+  ! create output fileset
+  ncout =create(cfileout, cfilu, npiglo,npjglo,npk,cdep='depthw')
+  ierr= createvar(ncout ,typvar,1, ipk,id_varout )
+  ierr= putheadervar(ncout, 'dummy', npiglo, npjglo, npk, glamt, gphit, gdepw )
+  
+  tim=getvar1d(cfilu,trim(ctim),nt) !LB
+  ierr=putvar1d(ncout,tim,nt,'T') !LB
+
+  !tim=getvar1d(cfilu,'time_counter',1)
+  !ierr=putvar1d(ncout,tim,1,'T')
+
+
+
+  DO jt = 1, nt !LB
+     
+     PRINT *, 'jt=',jt
+     
+     wn(:,:,:) = 0.
+     
+     ! Main level loop from bottom to top
+     DO jk = npk-1, 1, -1
+
+        !print *,' jk = ', jk
+        
+        ! veloccities at level jk
+        un(:,:) =  getvar(cfilu, cvaru, jk ,npiglo,npjglo, ktime=jt)
+        vn(:,:) =  getvar(cfilv, cvarv, jk ,npiglo,npjglo, ktime=jt)
+        
+        ! e3 metrics at level jk ( Partial steps)
+        e3u(:,:) = getvar(czgr,'e3u_0',jk ,npiglo,npjglo, ldiom=.true.) 
+        e3v(:,:) = getvar(czgr,'e3v_0',jk ,npiglo,npjglo, ldiom=.true.) 
+        e3t(:,:) = getvar(czgr,'e3t_0',jk ,npiglo,npjglo, ldiom=.true.) 
+
+        
+        ! 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
+        
+        ! Computation from the bottom
+        wn(:,:,itop) = wn(:,:,ibot) - e3t(:,:) * hdivn(:,:)
+        
+        ! write wn  on file at level jk (This coculd be epensive at it writes from the bottom ...
+        ierr = putvar(ncout, id_varout(1) ,wn(:,:,itop), jk ,npiglo, npjglo, jt) !LB
+        
+        ! swap top and bottom index
+        itmp=itop ; itop = ibot ; ibot = itmp 
+        
+     ENDDO  ! loop to next level
+
+  END DO
+  ierr = closeout(ncout)
+  
+  
+END PROGRAM cdfw
+

+ 286 - 0
cdftools_light/src/cdfzonalmean.f90

@@ -0,0 +1,286 @@
+PROGRAM cdfzonalmean
+  !!-------------------------------------------------------------------
+  !!               ***  PROGRAM cdfzonalmean  ***
+  !!
+  !!  **  Purpose  :  Compute the zonal mean 
+  !!  
+  !!  **  Method   :  
+  !!                  Results are saved on zonalmean.nc file with 
+  !!                  variables name respectively as follow:
+  !!                  same as input except that the 2 first char are
+  !!                  changed to zo. Then a suffix is append to the
+  !!                  name of the variable : glo atl inp ind and pac
+  !!                  if a subbasin mask is given on input., else
+  !!                  the suffix glo is used. Example :
+  !!                  sosaline_glo sosaline_atl etc ...
+  !!
+  !!
+  !! history ;
+  !!  Original :  J.M. Molines (nov. 2005) 
+  !!  Modified :  P.   Mathiot (June 2007) Update for forcing fields format
+  !!                                       + for many time steps
+  !!-------------------------------------------------------------------
+  !!  $Rev: 256 $
+  !!  $Date: 2009-07-21 17:49:27 +0200 (Tue, 21 Jul 2009) $
+  !!  $Id: cdfzonalmean.f90 256 2009-07-21 15:49:27Z molines $
+  !!--------------------------------------------------------------
+  !! * Modules used
+  USE cdfio
+
+  !! * Local variables
+  IMPLICIT NONE
+  INTEGER   :: npbasins=1, ivar = 0                !: number of subbasin, number of output var
+  INTEGER   :: jbasin, jj, jk ,ji ,jvar ,jjvar,jkk !: dummy loop index
+  INTEGER   :: jt                                  !: dummy loop index
+  INTEGER   :: ierr                                !: working integer
+  INTEGER   :: narg, iargc                         !: command line 
+  INTEGER   :: npiglo,npjglo, npk, nt              !: size of the domain
+  INTEGER   :: ncout
+  INTEGER   :: nvars , mvar                        !: number of variables in the file
+  INTEGER, DIMENSION(:), ALLOCATABLE ::  ipk, ijvar, ipko, id_varout    !: jpbasin x nvar
+  INTEGER, DIMENSION(2)              ::  iloc
+
+  REAL(KIND=4), DIMENSION (:,:),     ALLOCATABLE ::  e1, e2, gphi, zv !:  metrics, velocity
+  REAL(KIND=4), DIMENSION (:,:),     ALLOCATABLE ::  dumlon              !: dummy longitude = 0.
+  REAL(KIND=4), DIMENSION (:,:),     ALLOCATABLE ::  dumlat              !: latitude for i = north pole
+  REAL(KIND=4), DIMENSION (:,:),     ALLOCATABLE ::  zmaskvar
+  REAL(KIND=4), DIMENSION (:),       ALLOCATABLE ::  gdep                !: gdept or gdepw
+  REAL(KIND=4), DIMENSION (:,:,:),   ALLOCATABLE ::  zmask               !:  jpbasins x npiglo x npjglo
+  REAL(KIND=4), DIMENSION (1)                    ::  tim
+  REAL(KIND=4)                                   :: spval=99999.
+
+  REAL(KIND=8), DIMENSION (:,:),   ALLOCATABLE ::  zomsf , area        !: jpbasins x npjglo x npk
+
+  CHARACTER(LEN=256) :: cfilev , cfileoutnc='zonalmean.nc', cdum
+  CHARACTER(LEN=256) :: coordhgr='mesh_hgr.nc',  coordzgr='mesh_zgr.nc',cmaskfil='mask.nc',cbasinmask='none'
+  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE   :: cvarname             !: array of var name for input
+  CHARACTER(LEN=256), DIMENSION(:), ALLOCATABLE   :: cvarnameo             !: array of var name for output
+  TYPE(variable), DIMENSION(:), ALLOCATABLE   :: typvar                  !: structure for attributes
+  TYPE(variable), DIMENSION(:), ALLOCATABLE   :: typvaro                 !: structure for attributes
+  CHARACTER(LEN=10) :: ce1, ce2, cphi, cdep,cmask, cdepo
+  CHARACTER(LEN=4),DIMENSION(5) :: cbasin=(/'_glo','_atl','_inp','_ind','_pac'/)
+
+  LOGICAL :: lrevert_dep = .TRUE.         !: flag to revert the order of depth in the output file (plotting facility)
+  LOGICAL :: lforcing    = .FALSE.
+
+  !!  Read command line and output usage message if not compliant.
+  narg= iargc()
+  IF ( narg == 0 ) THEN
+     PRINT *,' Usage : cdfzonalmean  file  T | U | V | F | W [new_maskglo.nc]'
+     PRINT *,' Computes the zonal mean '
+     PRINT *,' If no new_maskglo specified, assume global '
+     PRINT *,' Files mesh_hgr.nc, mesh_zgr.nc ,mask.nc '
+     PRINT *,'  must be in the current directory'
+     PRINT *,' Output on zonalmean.nc: '
+     PRINT *,'      variables zoxxxx_glo  : Global ocean '
+     PRINT *,'      variables zoxxxx_atl  : Atlantic Ocean '
+     PRINT *,'      variables zoxxxx_inp  : Indo Pacific '
+     PRINT *,'      variables zoxxxx_ind  : Indian Ocean alone'
+     PRINT *,'      variables zoxxxx_pac  : Pacific Ocean alone'
+     PRINT *,'  Depth variable output is negative (standard) unless '
+     PRINT *,'  you recompile the tool with lrevert_dep=.false.'
+     STOP
+  ENDIF
+
+  CALL getarg (1, cfilev)
+  CALL getarg (2, cdum )
+
+  ! set the metrics according to C grid point
+  SELECT CASE (cdum)
+  CASE ('T', 't', 'S', 's')
+     ce1='e1t'
+     ce2='e2t'
+     cdep='gdept'
+     cdepo='deptht'
+     cphi='gphit'
+     cmask='tmask'
+  CASE ('U', 'u')
+     ce1='e1u'
+     ce2='e2u'
+     cdep='gdepu'
+     cdepo='depthu'
+     cphi='gphiu'
+     cmask='umask'
+  CASE ('V', 'v')
+     ce1='e1v'
+     ce2='e2v'
+     cdep='gdepv'
+     cdepo='depthv'
+     cphi='gphiv'
+     cmask='vmask'
+  CASE ('F', 'f')
+     ce1='e1f'
+     ce2='e2f'
+     cdep='gdepf'
+     cdepo='deptht'
+     cphi='gphif'
+     cmask='fmask'
+  CASE ('W', 'w')
+     ce1='e1t'
+     ce2='e2t'
+     cdep='gdepw'
+     cdepo='depthw'
+     cphi='gphit'
+     cmask='tmask'
+  CASE DEFAULT
+     PRINT *, ' C grid:', TRIM(cdum),' point not known!'
+     STOP
+  END SELECT
+
+  ! Read sub_basin file name (optional)
+  IF (narg == 3 ) THEN
+     CALL getarg(3, cbasinmask)
+     npbasins=5
+  ENDIF
+
+  nvars  = getnvar(cfilev)
+  ALLOCATE ( cvarname(nvars)          ,ipk(nvars), ijvar(nvars), typvar(nvars)  )
+  ALLOCATE ( cvarnameo(npbasins*nvars),ipko(npbasins*nvars),id_varout(npbasins*nvars) )
+  ALLOCATE ( typvaro(npbasins*nvars))
+  cvarname(1:nvars) = getvarname(cfilev,nvars,typvar)
+  ipk(1:nvars) = getipk(cfilev,nvars)
+
+  ! buildt output filename
+  ivar = 0
+  mvar = 0
+  DO jvar = 1,nvars
+     ! skip variables such as nav_lon, nav_lat, time_counter deptht ...
+     IF (ipk(jvar) == 0 ) THEN
+        cvarname(jvar)='none'
+     ELSE
+        mvar = mvar + 1       ! count for valid input variables
+        ijvar(mvar) = jvar    ! use indirect adressing for those variables
+        DO jbasin=1,npbasins
+           ivar=ivar + 1      ! count for output variables
+           cvarnameo(ivar)='zo'//TRIM(cvarname(jvar)(3:))//TRIM(cbasin(jbasin) )
+           ! intercept case of duplicate zonal name
+           IF (cvarname(jvar) == 'iowaflup' ) cvarnameo(ivar)='zowaflio'//TRIM(cbasin(jbasin) )
+           IF (cvarname(jvar) == 'cfc11' ) cvarnameo(ivar)='zocfc11'//TRIM(cbasin(jbasin) )
+           IF (cvarname(jvar) == 'bombc14' ) cvarnameo(ivar)='zobc14'//TRIM(cbasin(jbasin) )
+           IF (cvarname(jvar) == 'invcfc' ) cvarnameo(ivar)='zoinvcfc'//TRIM(cbasin(jbasin) )
+           IF (cvarname(jvar) == 'invc14' ) cvarnameo(ivar)='zoinvc14'//TRIM(cbasin(jbasin) )
+           IF (cvarname(jvar) == 'qtrcfc' ) cvarnameo(ivar)='zoqtrcfc'//TRIM(cbasin(jbasin) )
+           IF (cvarname(jvar) == 'qtrc14' ) cvarnameo(ivar)='zoqtrc14'//TRIM(cbasin(jbasin) )
+           IF (cvarname(jvar) == 'qintcfc' ) cvarnameo(ivar)='zoqintcfc'//TRIM(cbasin(jbasin) )
+           IF (cvarname(jvar) == 'qintc14' ) cvarnameo(ivar)='zoqintc14'//TRIM(cbasin(jbasin) )
+           typvaro(ivar)%name=cvarnameo(ivar)
+           ! units can be build automatically ( the same as original variable)
+           typvaro(ivar)%units=typvar(jvar)%units
+           ! missing value, valid min and valid max : idem original field
+           typvaro(ivar)%missing_value=spval
+           typvaro(ivar)%valid_min=typvar(jvar)%valid_min
+           typvaro(ivar)%valid_max=typvar(jvar)%valid_max
+           ! longname : prefix=Zonal_Mean_   suffix=TRIM(cbasin(jbasin)
+           typvaro(ivar)%long_name='Zonal_Mean_'//TRIM(typvar(jvar)%long_name)//TRIM(cbasin(jbasin) )
+           ! shortname=name
+           typvaro(ivar)%short_name=typvaro(ivar)%name
+           ! online operation : N/A (as usual ...)
+           typvaro(ivar)%online_operation='/N/A'
+           ! axis : either TY( original 2D)  or TZY (original 3D)
+           IF (ipk(jvar) == 1 ) THEN
+             typvaro(ivar)%axis='TY'
+           ELSE
+             typvaro(ivar)%axis='TZY'
+           ENDIF
+     
+           ipko(ivar)=ipk(jvar)
+        END DO
+     ENDIF
+  END DO
+
+  npiglo= getdim (cfilev,'x')
+  npjglo= getdim (cfilev,'y')
+  npk   = getdim (cfilev,'depth')
+  nt    = getdim (cfilev,'time_counter')
+
+  PRINT *, 'npiglo=', npiglo
+  PRINT *, 'npjglo=', npjglo
+  PRINT *, 'npk   =', npk
+  PRINT *, 'nt    =', nt
+  ! if forcing fields, npk=0, assume 1
+  IF (npk==0) THEN
+     npk = 1 
+     lforcing= .TRUE.
+     PRINT *,' It is a forcing field, assume npk=1 and gdep=0'
+  END IF
+  ! Allocate arrays
+  ALLOCATE ( zmask(npbasins,npiglo,npjglo) )
+  ALLOCATE ( zv(npiglo,npjglo) )
+  ALLOCATE ( zmaskvar(npiglo,npjglo) )
+  ALLOCATE ( e1(npiglo,npjglo),e2(npiglo,npjglo), gphi(npiglo,npjglo) ,gdep(npk) )
+  ALLOCATE ( zomsf( npjglo, npk) ,area( npjglo, npk) )
+  ALLOCATE ( dumlon(1,npjglo) , dumlat(1,npjglo))
+
+
+  ! get the metrics
+  e1(:,:)   = getvar(coordhgr, ce1, 1,npiglo,npjglo) 
+  e2(:,:)   = getvar(coordhgr, ce2, 1,npiglo,npjglo) 
+  gphi(:,:) = getvar(coordhgr, cphi, 1,npiglo,npjglo)
+  IF (.NOT. lforcing) gdep(:)   = getvare3(coordzgr, cdep ,npk)
+  IF (lforcing)  gdep(:)   = 0
+  IF ( lrevert_dep ) gdep(:)   = -1.*  gdep(:)     ! helps for plotting the results
+
+  ! Look for the i-index that go through the North Pole
+  iloc        = MAXLOC(gphi)
+  dumlat(1,:) = gphi(iloc(1),:)
+  dumlon(:,:) = 0.   ! set the dummy longitude to 0
+
+  ! create output fileset
+  ncout = create(cfileoutnc, cfilev, 1,npjglo,npk,cdep=cdepo)
+  ierr  = createvar(ncout ,typvaro,ivar, ipko,id_varout )
+  ierr  = putheadervar(ncout, cfilev,1,npjglo,npk,pnavlon=dumlon,pnavlat=dumlat,pdep=gdep)
+  tim   = getvar1d(cfilev,'time_counter',1)
+  ierr  = putvar1d(ncout,tim,1,'T')
+
+  ! reading the surface mask masks
+  ! 1 : global ; 2 : Atlantic ; 3 : Indo-Pacif ; 4 : Indian ; 5 : Pacif
+  zmask(1,:,:) = getvar(cmaskfil,cmask,1,npiglo,npjglo)
+  IF ( cbasinmask /= 'none' ) THEN
+     zmask(2,:,:) = getvar(cbasinmask,'tmaskatl',1,npiglo,npjglo)
+     zmask(4,:,:) = getvar(cbasinmask,'tmaskind',1,npiglo,npjglo)
+     zmask(5,:,:) = getvar(cbasinmask,'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
+
+  ! main computing loop
+  ivar = 0
+  DO jjvar = 1, mvar
+     jvar = ijvar(jjvar)
+     DO jt = 1,nt
+        IF (MOD(jt,100)==0) PRINT *, jt,'/',nt
+        DO jkk = 1, ipk(jvar)
+           PRINT *,TRIM(cvarname(jvar)), ' level ',jkk
+           ! Get variables and mask at level jk
+           zv(:,:)       = getvar(cfilev,   cvarname(jvar),jkk ,npiglo,npjglo,ktime=jt)
+           zmaskvar(:,:) = getvar(cmaskfil, cmask,         jkk ,npiglo,npjglo)
+           
+           ! For all basins 
+           DO jbasin = 1, npbasins
+              zomsf(:,:) = 0.d0
+              area(:,:) = 0.d0
+              ! integrates 'zonally' (along i-coordinate)
+              DO ji=1,npiglo
+                 DO jj=1,npjglo
+                    zomsf(jj,jkk) = zomsf(jj,jkk) + e1(ji,jj)*e2(ji,jj)* zmask(jbasin,ji,jj)*zmaskvar(ji,jj)*zv(ji,jj)
+                    area(jj,jkk)  =  area(jj,jkk) + e1(ji,jj)*e2(ji,jj)* zmask(jbasin,ji,jj)*zmaskvar(ji,jj)
+                 END DO
+              END DO
+
+              ! compute the mean value if the area is not 0, else assign spval
+              WHERE (area /= 0 ) 
+                 zomsf=zomsf/area
+              ELSEWHERE
+                 zomsf=spval
+              ENDWHERE
+              ivar=  (jjvar-1)*npbasins + jbasin
+              ierr = putvar (ncout, id_varout(ivar),REAL(zomsf(:,jkk)), jkk,1,npjglo, ktime=jt)
+           END DO  !next basin
+        END DO  ! next k 
+     END DO ! next time
+  END DO ! next variable
+
+  ierr = closeout(ncout)
+
+END PROGRAM cdfzonalmean

+ 340 - 0
cdftools_light/src/eos.f90

@@ -0,0 +1,340 @@
+MODULE eos
+  !!  $Rev: 234 $
+  !!  $Date: 2009-04-28 19:33:08 +0200 (Tue, 28 Apr 2009) $
+  !!  $Id: eos.f90 234 2009-04-28 17:33:08Z molines $
+  !!--------------------------------------------------------------
+
+IMPLICIT NONE
+PRIVATE
+PUBLIC sigma0, eosbn2, sigmai, albet, beta
+
+CONTAINS
+     FUNCTION sigma0 ( ptem, psal, kpi,kpj)
+       !! --------------------------------------------------------------------
+       !! ** Purpose :   Compute the in situ density (ratio rho/rau0) and the
+       !!      potential volumic mass (Kg/m3) from potential temperature and
+       !!      salinity fields using an equation of state defined through the
+       !!     namelist parameter neos.
+       !!
+       !! ** Method  :
+       !!       Jackett and McDougall (1994) equation of state.
+       !!         the in situ density is computed directly as a function of
+       !!         potential temperature relative to the surface (the opa t
+       !!         variable), salt and pressure (assuming no pressure variation
+       !!         along geopotential surfaces, i.e. the pressure p in decibars
+       !!         is approximated by the depth in meters.
+       !!              prd(t,s,p) = ( rho(t,s,p) - rau0 ) / rau0
+       !!              rhop(t,s)  = rho(t,s,0)
+       !!         with pressure                      p        decibars
+       !!              potential temperature         t        deg celsius
+       !!              salinity                      s        psu
+       !!              reference volumic mass        rau0     kg/m**3
+       !!              in situ volumic mass          rho      kg/m**3
+       !!              in situ density anomalie      prd      no units
+       !! --------------------------------------------------------------------
+ 
+       !! * Arguments
+       INTEGER,INTENT(in) :: kpi,kpj  !: dimension of 2D arrays
+       REAL(KIND=4), DIMENSION(kpi,kpj), INTENT(in) :: ptem, psal
+       REAL(KIND=8), DIMENSION(kpi,kpj) :: sigma0
+ 
+       !! * local variables
+       INTEGER :: ji,jj 
+       REAL(KIND=8), DIMENSION (kpi,kpj) :: zws
+       REAL(KIND=8) :: zt, zs, zsr, zr1, zr2, zr3, zr4, zrau0=1000.
+ 
+ 
+       zws = 0.d0
+       sigma0 = 0.d0
+       DO jj = 1, kpj
+          DO ji = 1, kpi
+             zws(ji,jj) = SQRT( ABS( psal(ji,jj) ) )
+          END DO
+       END DO
+ 
+       DO jj = 1, kpj
+          !
+          DO ji = 1, kpi
+ 
+             zt = ptem (ji,jj)            ! interpolated T
+             zs = psal (ji,jj)            ! interpolated S
+             zsr= zws(ji,jj)            ! square root of interpolated S
+ 
+             ! compute volumic mass pure water at atm pressure
+             zr1 = ( ( ( ( 6.536332e-9*zt-1.120083e-6 )*zt+1.001685e-4)*zt   &
+                  -9.095290e-3 )*zt+6.793952e-2 )*zt+999.842594
+             ! seawater volumic mass atm pressure
+             zr2= ( ( ( 5.3875e-9*zt-8.2467e-7 )*zt+7.6438e-5 ) *zt   &
+                  -4.0899e-3 ) *zt+0.824493
+             zr3= ( -1.6546e-6*zt+1.0227e-4 ) *zt-5.72466e-3
+             zr4= 4.8314e-4
+ 
+             ! potential volumic mass (reference to the surface)
+             sigma0(ji,jj) = ( zr4*zs + zr3*zsr + zr2 ) *zs + zr1 -zrau0
+          END DO
+       END DO
+ 
+     END FUNCTION sigma0
+     
+     FUNCTION sigmai ( ptem, psal, pref, kpi,kpj)
+       !! --------------------------------------------------------------------
+       !! ** Purpose :   Compute the  density referenced to pref (ratio rho/rau0) 
+       !!       from potential temperature and
+       !!      salinity fields using an equation of state defined through the
+       !!     namelist parameter neos.
+       !!
+       !! ** Method  :
+       !!       Jackett and McDougall (1994) equation of state.
+       !!         the in situ density is computed directly as a function of
+       !!         potential temperature relative to the surface (the opa t
+       !!         variable), salt and pressure (assuming no pressure variation
+       !!         along geopotential surfaces, i.e. the pressure p in decibars
+       !!         is approximated by the depth in meters.
+       !!              prd(t,s,p) = ( rho(t,s,p) - rau0 ) / rau0
+       !!              rhop(t,s)  = rho(t,s,0)
+       !!         with pressure                      p        decibars
+       !!              potential temperature         t        deg celsius
+       !!              salinity                      s        psu
+       !!              reference volumic mass        rau0     kg/m**3
+       !!              in situ volumic mass          rho      kg/m**3
+       !!              in situ density anomalie      prd      no units
+       !! --------------------------------------------------------------------
+ 
+       !! * Arguments
+       INTEGER,INTENT(in) :: kpi,kpj  !: dimension of 2D arrays
+       REAL(KIND=4), DIMENSION(kpi,kpj), INTENT(in) :: ptem, psal
+       REAL(KIND=4),                     INTENT(in) :: pref      !: reference pressure (meters or db)
+       REAL(KIND=8), DIMENSION(kpi,kpj) :: sigmai
+ 
+       REAL(kind=8),PARAMETER :: dpr4=4.8314d-4,dpd=-2.042967d-2 , dprau0 = 1000;
+
+       !! * local variables
+       INTEGER :: ji,jj 
+       REAL(KIND=8), DIMENSION (kpi,kpj)  ::  dlrs
+       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 = 0.d0
+       DO jj = 1, kpj
+          DO ji = 1, kpi
+             dlrs(ji,jj) = SQRT( ABS( psal(ji,jj) ) )
+          END DO
+       END DO
+ 
+       DO jj=1,kpj
+         DO ji=1,kpi
+
+! Convert T and S to double precision.
+        dlt=DBLE(ptem(ji,jj))
+        dls=DBLE(psal(ji,jj))
+
+
+! Compute the volumic mass of pure water at atmospheric pressure.
+        dlr1=((((6.536332d-9*dlt-1.120083d-6)&
+                *dlt+1.001685d-4)&
+               *dlt-9.095290d-3)&
+              *dlt+6.793952d-2)&
+             *dlt+999.842594d0
+
+! Compute the seawater volumic mass at atmospheric pressure.
+        dlr2=(((5.3875d-9*dlt-8.2467d-7)&
+               *dlt+7.6438d-5)&
+              *dlt-4.0899d-3)&
+             *dlt+0.824493d0
+
+        dlr3=(-1.6546d-6*dlt+1.0227d-4)&
+             *dlt-5.72466d-3
+
+! Compute the potential volumic mass (referenced to the surface).
+        dlrhop=(dpr4*dls+dlr3*dlrs(ji,jj)+dlr2)*dls+dlr1
+
+! Compute the compression terms.
+        dle=(-3.508914d-8*dlt-1.248266d-8)&
+            *dlt-2.595994d-6
+
+        dlbw=(1.296821d-6*dlt-5.782165d-9)&
+             *dlt+1.045941d-4
+
+        dlb=dlbw+dle*dls
+
+        dlc=(-7.267926d-5*dlt+2.598241d-3 )&
+            *dlt+0.1571896d0
+
+        dlaw=((5.939910d-6*dlt+2.512549d-3)&
+              *dlt-0.1028859d0)&
+             *dlt-4.721788d0
+
+        dla=(dpd*dlrs(ji,jj)+dlc)*dls+dlaw
+
+        dlb1=(-0.1909078d0*dlt+7.390729d0)&
+             *dlt-55.87545d0
+
+        dla1=((2.326469d-3*dlt+1.553190d0)&
+              *dlt-65.00517d0)&
+             *dlt+1044.077d0
+
+        dlkw=(((-1.361629d-4*dlt-1.852732d-2)&
+               *dlt-30.41638d0)&
+              *dlt+2098.925d0)&
+             *dlt+190925.6d0
+
+        dlk0=(dlb1*dlrs(ji,jj)+dla1)*dls+dlkw
+
+! Compute the potential density anomaly.
+        sigmai(ji,jj)=dlrhop/(1.0d0-dlref/(dlk0-dlref*(dla-dlref*dlb)))&
+                       -dprau0
+
+      ENDDO
+    ENDDO
+ 
+     END FUNCTION sigmai
+
+     FUNCTION eosbn2 ( ptem, psal, pdep,pe3w, kpi,kpj,kup,kdown)
+       !! ----------------------------------------------------------------------
+       !! ** Purpose :   Compute the local Brunt-Vaisala frequency at the time-
+       !!      step of the input arguments
+       !!
+       !! ** Method :
+       !!       *  UNESCO sea water properties
+       !!         The brunt-vaisala frequency is computed using the
+       !!      polynomial expression of McDougall (1987):
+       !!            N^2 = grav * beta * ( alpha/beta*dk[ t ] - dk[ s ] )/e3w
+       !!---------------------------------------------------------------------
+       ! * Arguments
+       INTEGER, INTENT(in)    :: kpi,kpj
+       INTEGER, INTENT(in)    :: kup,kdown
+       REAL(KIND=4), DIMENSION(kpi,kpj,2), INTENT(in) :: ptem, psal
+       REAL(KIND=4), DIMENSION(kpi,kpj), INTENT(in) ::  pe3w
+       REAL(KIND=4)  :: pdep
+       REAL(KIND=4), DIMENSION(kpi,kpj) :: eosbn2
+ 
+       ! * Local variables
+       INTEGER  ::   ji, jj         ! dummy loop indices
+       REAL(KIND=8) ::   &
+            zgde3w, zt, zs, zh,  &  ! temporary scalars
+            zalbet, zbeta           !    "
+       REAL(KIND=8) :: grav=9.81
+ 
+       zh = pdep
+       DO jj = 1, kpj
+          DO ji = 1, kpi
+             zgde3w = grav / pe3w(ji,jj)
+             zt = 0.5 * ( ptem(ji,jj,kup) + ptem(ji,jj,kdown) )          ! potential temperature at w-point
+             zs = 0.5 * ( psal(ji,jj,kup) + psal(ji,jj,kdown) ) - 35.0   ! salinity anomaly (s-35) at w-point
+ 
+             zalbet = ( ( ( - 0.255019e-07 * zt + 0.298357e-05 ) * zt   &   ! ratio alpha/beta
+                  &                               - 0.203814e-03 ) * zt   &
+                  &                               + 0.170907e-01 ) * zt   &
+                  &   + 0.665157e-01                                      &
+                  &   +     ( - 0.678662e-05 * zs                         &
+                  &           - 0.846960e-04 * zt + 0.378110e-02 ) * zs   &
+                  &   +   ( ( - 0.302285e-13 * zh                         &
+                  &           - 0.251520e-11 * zs                         &
+                  &           + 0.512857e-12 * zt * zt           ) * zh   &
+                  &           - 0.164759e-06 * zs                         &
+                  &        +(   0.791325e-08 * zt - 0.933746e-06 ) * zt   &
+                  &                               + 0.380374e-04 ) * zh
+ 
+             zbeta  = ( ( -0.415613e-09 * zt + 0.555579e-07 ) * zt      &   ! beta
+                  &                            - 0.301985e-05 ) * zt      &
+                  &   + 0.785567e-03                                      &
+                  &   + (     0.515032e-08 * zs                           &
+                  &         + 0.788212e-08 * zt - 0.356603e-06 ) * zs     &
+                  &   +(  (   0.121551e-17 * zh                           &
+                  &         - 0.602281e-15 * zs                           &
+                  &         - 0.175379e-14 * zt + 0.176621e-12 ) * zh     &
+                  &                             + 0.408195e-10   * zs     &
+                  &     + ( - 0.213127e-11 * zt + 0.192867e-09 ) * zt     &
+                  &                             - 0.121555e-07 ) * zh
+ 
+             eosbn2(ji,jj) = zgde3w * zbeta            &   ! N^2
+                  &          * ( zalbet * ( ptem(ji,jj,kup) - ptem(ji,jj,kdown) )   &
+                  &                     - ( psal(ji,jj,kup) - psal(ji,jj,kdown) ) )
+          END DO
+       END DO
+ 
+ 
+     END FUNCTION eosbn2
+
+     FUNCTION albet(  ptem, psal, pdep, kpi,kpj)
+       !!-------------------------------------------------------------------------------------------
+       !!                 *** FUNCTION  albet ***
+       !!
+       !!     * Purpose: Compute the ratio alpha/beta 
+       !! -----------------------------------------------------------------------------------------
+       !! * Arguments
+       INTEGER, INTENT(in) :: kpi, kpj
+       REAL(KIND=4), DIMENSION(kpi,kpj),INTENT(in) :: ptem, psal
+       REAL(KIND=4), INTENT(in) :: pdep
+
+       REAL(KIND=8), DIMENSION(kpi,kpj) :: albet
+
+       !! * Local variables
+       INTEGER :: ji,jj
+       REAL(KIND=8)  :: zt, zs, zh
+       
+       zh = pdep
+       DO ji=1,kpi
+          DO jj=1,kpj
+             zt =  ptem(ji,jj)         ! potential temperature
+             zs =  psal(ji,jj)- 35.0   ! salinity anomaly (s-35)
+
+             albet(ji,jj) = ( ( ( - 0.255019e-07 * zt + 0.298357e-05 ) * zt   &   ! ratio alpha/beta
+                  &                               - 0.203814e-03 ) * zt   &
+                  &                               + 0.170907e-01 ) * zt   &
+                  &   + 0.665157e-01                                      &
+                  &   +     ( - 0.678662e-05 * zs                         &
+                  &           - 0.846960e-04 * zt + 0.378110e-02 ) * zs   &
+                  &   +   ( ( - 0.302285e-13 * zh                         &
+                  &           - 0.251520e-11 * zs                         &
+                  &           + 0.512857e-12 * zt * zt           ) * zh   &
+                  &           - 0.164759e-06 * zs                         &
+                  &        +(   0.791325e-08 * zt - 0.933746e-06 ) * zt   &
+                  &                               + 0.380374e-04 ) * zh
+          END DO
+       END DO
+
+     END FUNCTION albet
+     
+     FUNCTION beta (  ptem, psal, pdep, kpi,kpj)
+       !!-------------------------------------------------------------------------------------------
+       !!                 *** FUNCTION  beta ***
+       !!
+       !!     * Purpose: Compute the beta
+       !! -----------------------------------------------------------------------------------------
+       !! * Arguments
+       INTEGER, INTENT(in) :: kpi, kpj
+       REAL(KIND=4), DIMENSION(kpi,kpj),INTENT(in) :: ptem, psal
+       REAL(KIND=4), INTENT(in) :: pdep
+
+       REAL(KIND=8), DIMENSION(kpi,kpj) :: beta
+
+       !! * Local variables
+       INTEGER :: ji,jj
+       REAL(KIND=8)  :: zt, zs, zh
+
+       zh = pdep
+       DO ji=1,kpi
+          DO jj=1,kpj
+             zt =  ptem(ji,jj)         ! potential temperature
+             zs =  psal(ji,jj)- 35.0   ! salinity anomaly (s-35)
+
+             beta(ji,jj)  = ( ( -0.415613e-09 * zt + 0.555579e-07 ) * zt      &   ! beta
+                  &                            - 0.301985e-05 ) * zt      &
+                  &   + 0.785567e-03                                      &
+                  &   + (     0.515032e-08 * zs                           &
+                  &         + 0.788212e-08 * zt - 0.356603e-06 ) * zs     &
+                  &   +(  (   0.121551e-17 * zh                           &
+                  &         - 0.602281e-15 * zs                           &
+                  &         - 0.175379e-14 * zt + 0.176621e-12 ) * zh     &
+                  &                             + 0.408195e-10   * zs     &
+                  &     + ( - 0.213127e-11 * zt + 0.192867e-09 ) * zt     &
+                  &                             - 0.121555e-07 ) * zh
+          END DO
+       END DO
+
+     END FUNCTION beta
+
+END MODULE eos

+ 1738 - 0
cdftools_light/src/io_ezcdf.f90

@@ -0,0 +1,1738 @@
+MODULE io_ezcdf
+
+   USE netcdf
+
+   !! Netcdf input/output
+   !!
+   !! Author: Laurent Brodeau, 2010
+
+   IMPLICIT NONE
+
+
+   !INTERFACE PIECDF
+   !   module procedure P2D_T
+   !   module procedure P3D_T
+   !END INTERFACE PIECDF
+
+
+   PRIVATE
+
+   !INTERFACE FIECDF
+   !   module procedure ctest_coor
+   !END INTERFACE FIECDF
+
+
+
+   !! List of public routines
+   !! =======================
+   PUBLIC :: dims,      &
+      &    get_sf_ao,        &
+      &    getvar_1d,        &
+      &    getvar_2d,        &
+      &    getvar_2d_r8,     & ! Mostly for 2D coordinates
+      &    getvar_3d,        &
+      &    getmask_2d,       &
+      &    getmask_3d,       &
+      &    p2d_t,            &
+      &    p3d_t,            &
+      &    p3d_t_4v,         &
+      &    check_4_miss,     &
+      &    get_var_info,     &
+      &    prtmask,          &
+      &    phovmoller,       &
+      &    who_is_mv
+   !!===========================
+
+   CHARACTER(len=80) :: cv_misc
+
+   CHARACTER(len=2) :: cdt  ! '1d' or '2d'
+
+   REAL(8), DIMENSION(3,2) :: vextrema
+
+   INTEGER :: &
+      &    nd,    &
+      &    id_f, id_v,           &   !: ID for a variable
+      &    id_x, id_y, id_z, id_t,     &
+      &    id_lo, id_la, &
+      &    id_dpt, id_tim
+
+   REAL(4)               :: rmin, rmax, scale_f, add_off
+
+   CHARACTER(len=400)    :: crtn, cu
+
+   CHARACTER(LEN=400), PARAMETER   ::     &
+      &    cabout = 'File created by BaraKuda (https://github.com/brodeau/barakuda)'
+
+   INTEGER :: ji, jj, jk
+
+   INTEGER, PARAMETER :: nmval = 3
+   CHARACTER(len=80), DIMENSION(nmval), PARAMETER :: &
+      &     c_nm_missing_val = (/ 'FillValue ', '_FillValue', '_Fillvalue' /)
+
+   INTEGER(2), PARAMETER :: imv = 32767
+
+
+CONTAINS
+
+
+
+
+   SUBROUTINE DIMS(cf_in, cv_in, lx, ly, lz, lt)
+
+      !!-----------------------------------------------------------------------
+      !!
+      !! Updated August 2012, L. Brodeau
+      !!
+      !! This routine opens a netcdf file 'cf_in' to check the dimension
+      !! of the variable 'cv_in'. It then gives the length of each of the dimension,
+      !! if the length returns '-1' that means that the dimension does not exist
+      !!
+      !! example : if the variable has only 1 dimension, of length 132,
+      !!           DIMS will return lx=132, ly=-1, lz=-1, lt=-1
+      !!
+      !!
+      !! INPUT :
+      !! -------
+      !!          * cf_in       : name of the input file          (character)
+      !!          * cv_in       : name of the variable            (character)
+      !!
+      !! OUTPUT :
+      !! --------
+      !!          * lx      : first dimension                     (integer)
+      !!          * ly      : second dimension  (-1 if none)      (integer)
+      !!          * lz      : third dimension   (-1 if none)      (integer)
+      !!          * lt      : number of records (-1 if none)      (integer)
+      !!
+      !!------------------------------------------------------------------------
+
+      CHARACTER(len=*),   INTENT(in)  :: cf_in, cv_in
+      INTEGER,            INTENT(out) :: lx, ly, lz, lt
+
+      INTEGER, DIMENSION(:), ALLOCATABLE :: id_dim, nlen
+      INTEGER :: jdim, id_unlim_dim
+
+
+      crtn = 'DIMS'
+
+      lx = -1 ; ly = -1 ; lz = -1 ; lt = -1
+
+      CALL sherr( NF90_OPEN(cf_in, NF90_NOWRITE, id_f),  crtn,cf_in,cv_in)
+
+      ! Get ID of unlimited dimension
+      CALL sherr(  NF90_INQUIRE(id_f, unlimitedDimId = id_unlim_dim), crtn,cf_in,cv_in)
+
+
+      !! Getting variable ID:
+      CALL sherr( NF90_INQ_VARID(id_f,cv_in,id_v),              crtn,cf_in,cv_in)
+
+      !! nd => number of dimensions for the variable:
+      CALL sherr( NF90_INQUIRE_VARIABLE(id_f, id_v, ndims=nd),  crtn,cf_in,cv_in)
+
+      ALLOCATE ( id_dim(nd) , nlen(nd) )
+
+      !! Vector containing the IDs of each dimension (id_dim):
+      CALL sherr( NF90_INQUIRE_VARIABLE(id_f, id_v, dimids=id_dim),  crtn,cf_in,cv_in)
+
+      DO jdim = 1, nd
+         CALL sherr( NF90_INQUIRE_DIMENSION(id_f, id_dim(jdim), len=nlen(jdim)),   crtn,cf_in,cv_in)
+      END DO
+
+      SELECT CASE(nd)
+
+      CASE(1)
+         !! Purely 1D
+         lx = nlen(1)
+
+      CASE(2)
+         IF ( id_dim(2) == id_unlim_dim ) THEN
+            !! 1D with time records
+            lx = nlen(1) ; lt = nlen(2)
+         ELSE
+            !! 2D with no time records
+            lx = nlen(1) ; ly = nlen(2)
+         END IF
+
+      CASE(3)
+         IF ( id_dim(3) == id_unlim_dim ) THEN
+            !! 2D with time records
+            lx = nlen(1) ; ly = nlen(2) ; lt = nlen(3)
+         ELSE
+            !! 3D with no time records
+            lx = nlen(1) ; ly = nlen(2) ; lz = nlen(3)
+         END IF
+
+      CASE(4)
+         IF ( id_unlim_dim < 1 ) THEN
+            WRITE(6,*) 'ERROR: file ',trim(cf_in),' doesnt have an unlimited dimension (time record)!'
+         END IF
+
+         lx = nlen(1) ; ly = nlen(2)
+         IF ( id_dim(3) == id_unlim_dim ) THEN
+            lz = nlen(4) ; lt = nlen(3)   ! time record (unlimited dim) comes as 3rd dim and lz as 4th
+         ELSE
+            lz = nlen(3) ; lt = nlen(4)   ! time record (unlimited dim) comes as last dim and lz as 3rd
+         END IF
+
+      CASE DEFAULT
+         CALL print_err(crtn, 'the dimension is not realistic')
+
+      END SELECT
+
+      CALL sherr( NF90_CLOSE(id_f),  crtn,cf_in,cv_in)
+
+   END SUBROUTINE DIMS
+
+
+
+
+
+
+
+
+
+
+   SUBROUTINE GETVAR_1D(cf_in, cv_in, X)
+
+      !!-----------------------------------------------------------------------
+      !! This routine extract a variable 1D from a netcdf file
+      !!
+      !! INPUT :
+      !! -------
+      !!          * cf_in      : name of the input file             (character l=100)
+      !!          * cv_in      : name of the variable               (character l=20)
+      !!
+      !! OUTPUT :
+      !! --------
+      !!          * X         : 1D array contening the variable   (double)
+      !!
+      !!------------------------------------------------------------------------
+
+      CHARACTER(len=*),       INTENT(in)  :: cf_in, cv_in
+      REAL(8), DIMENSION (:), INTENT(out) ::  X
+
+      crtn = 'GETVAR_1D'
+
+      CALL sherr( NF90_OPEN(cf_in, NF90_NOWRITE, id_f),     crtn,cf_in,cv_in)
+
+      CALL sherr( NF90_INQ_VARID(id_f, trim(cv_in), id_v),  crtn,cf_in,cv_in)
+      CALL sherr( NF90_GET_VAR(id_f, id_v, X),              crtn,cf_in,cv_in)
+
+      CALL sherr( NF90_CLOSE(id_f),                         crtn,cf_in,cv_in)
+
+   END SUBROUTINE GETVAR_1D
+
+
+
+
+   SUBROUTINE GETVAR_2D(idx_f, idx_v, cf_in, cv_in, lt, kz, kt, X, jt1, jt2, lz)
+
+      !!-----------------------------------------------------------------------------
+      !! This routine extract a 2D field from a netcdf file
+      !! at a given time
+      !!
+      !! INPUT :
+      !! -------
+      !!          * idx_f    : ID of current file                  (integer)
+      !!          * idx_v    : ID of current variable              (integer)
+      !!          * cf_in      : name of the input file              (character)
+      !!          * cv_in      : name of the variable                (character)
+      !!          * lt        : time dimension of the variable     (integer)
+      !!          * kz        : level to extract                    (integer)
+      !!                      0 => input file does not have levels
+      !!
+      !!          * kt        : time snapshot to extract            (integer)
+      !!                      0 => input file does not have a time snapshot
+      !!                           (= old GETVAR_2D_NOTIME)
+      !!
+      !!
+      !! OUTPUT :
+      !! --------
+      !!          * X         : 2D array contening the variable     (real)
+      !!
+      !! OPTIONAL INPUT :
+      !! ----------------
+      !!          * jt1, jt2  : first and last time snapshot to extract
+      !!          *       lz  : number of levels to know when they are all read
+      !!                        so we can close the file
+      !!
+      !!------------------------------------------------------------------------
+
+      INTEGER,                   INTENT(inout) :: idx_f, idx_v
+      CHARACTER(len=*),          INTENT(in)    :: cf_in, cv_in
+      INTEGER,                   INTENT(in)    :: lt, kz, kt
+      REAL(4),  DIMENSION (:,:), INTENT(out)   :: X
+      INTEGER,       OPTIONAL,   INTENT(in)    :: jt1, jt2, lz
+
+      INTEGER :: &
+         & lx, &    ! x dimension of the variable        (integer)
+         & ly       ! y dimension of the variable        (integer)
+
+      INTEGER :: its, ite, kz_stop = 0
+
+      crtn = 'GETVAR_2D'
+
+      lx = size(X,1)
+      ly = size(X,2)
+
+      IF ( present(jt1).AND.present(jt2) ) THEN
+         its = jt1 ; ite = jt2
+      ELSE
+         its = 1   ; ite = lt
+      END IF
+
+      IF ( present(lz) ) kz_stop = lz
+
+      IF ( (kt == its).OR.(kt == 0) ) THEN   ! Opening file and defining variable :
+         CALL sherr( NF90_OPEN(cf_in, NF90_NOWRITE, idx_f),  crtn,cf_in,cv_in)
+         CALL sherr( NF90_INQ_VARID(idx_f, cv_in, idx_v),  crtn,cf_in,cv_in)
+      END IF
+
+      IF ( kz == 0 ) THEN    ! No levels
+
+         IF ( kt == 0 ) THEN
+            CALL sherr( NF90_GET_VAR(idx_f, idx_v, X, start=(/1,1/), count=(/lx,ly/)), &
+               &      crtn,cf_in,cv_in)
+         ELSEIF ( kt > 0 ) THEN
+            CALL sherr( NF90_GET_VAR(idx_f, idx_v, X, start=(/1,1,kt/), count=(/lx,ly,1/)), &
+               &      crtn,cf_in,cv_in)
+         END IF
+
+      ELSEIF ( kz > 0 ) THEN
+
+         IF ( kt == 0 ) THEN
+            CALL sherr( NF90_GET_VAR(idx_f, idx_v, X, start=(/1,1,kz/), count=(/lx,ly,1/)),  &
+               &      crtn,cf_in,cv_in)
+         ELSEIF ( kt > 0 ) THEN
+            CALL sherr( NF90_GET_VAR(idx_f, idx_v, X, start=(/1,1,kz,kt/), count=(/lx,ly,1,1/)), &
+               &      crtn,cf_in,cv_in)
+         END IF
+
+
+      END IF
+
+      ! Closing when needed:
+      IF ( (( kt == ite ).OR.( kt == 0 )).AND.(kz == kz_stop) )  THEN
+         CALL sherr( NF90_CLOSE(idx_f),  crtn,cf_in,cv_in)
+         idx_f = 0 ; idx_v = 0
+      END IF
+
+   END SUBROUTINE GETVAR_2D
+
+
+
+
+
+
+   SUBROUTINE GETVAR_2D_R8(idx_f, idx_v, cf_in, cv_in, lt, kz, kt, X, jt1, jt2, lz)
+
+      !!-----------------------------------------------------------------------------
+      !! This routine extract a 2D DOUBLE PRECISION field from a netcdf file
+      !! at a given time
+      !!
+      !! INPUT :
+      !! -------
+      !!          * idx_f    : ID of current file                  (integer)
+      !!          * idx_v    : ID of current variable              (integer)
+      !!          * cf_in      : name of the input file              (character)
+      !!          * cv_in      : name of the variable                (character)
+      !!          * lt        : time dimension of the variable     (integer)
+      !!          * kz        : level to extract                    (integer)
+      !!                      0 => input file does not have levels
+      !!
+      !!          * kt        : time snapshot to extract            (integer)
+      !!                      0 => input file does not have a time snapshot
+      !!                           (= old GETVAR_2D_NOTIME)
+      !!
+      !!
+      !! OUTPUT :
+      !! --------
+      !!          * X         : 2D array contening the variable     (double)
+      !!
+      !! OPTIONAL INPUT :
+      !! ----------------
+      !!          * jt1, jt2  : first and last time snapshot to extract
+      !!          *       lz  : number of levels to know when they are all read
+      !!                        so we can close the file
+      !!
+      !!------------------------------------------------------------------------
+
+      INTEGER,                  INTENT(inout) :: idx_f, idx_v
+      CHARACTER(len=*),         INTENT(in)    :: cf_in, cv_in
+      INTEGER,                  INTENT(in)    :: lt, kz, kt
+      REAL(8), DIMENSION (:,:), INTENT(out)   :: X
+      INTEGER,       OPTIONAL,  INTENT(in)    :: jt1, jt2, lz
+
+      INTEGER :: &
+         & lx, &    ! x dimension of the variable        (integer)
+         & ly       ! y dimension of the variable        (integer)
+
+      INTEGER :: its, ite, kz_stop = 0
+
+      crtn = 'GETVAR_2D_R8'
+
+      lx = size(X,1)
+      ly = size(X,2)
+
+      IF ( present(jt1).AND.present(jt2) ) THEN
+         its = jt1 ; ite = jt2
+      ELSE
+         its = 1   ; ite = lt
+      END IF
+
+      IF ( present(lz) ) kz_stop = lz
+
+      IF ( (kt == its).OR.(kt == 0) ) THEN   ! Opening file and defining variable :
+         CALL sherr( NF90_OPEN(cf_in, NF90_NOWRITE, idx_f),  crtn,cf_in,cv_in)
+         CALL sherr( NF90_INQ_VARID(idx_f, cv_in, idx_v),  crtn,cf_in,cv_in)
+      END IF
+
+      IF ( kz == 0 ) THEN    ! No levels
+
+         IF ( kt == 0 ) THEN
+            CALL sherr( NF90_GET_VAR(idx_f, idx_v, X, start=(/1,1/), count=(/lx,ly/)), &
+               &      crtn,cf_in,cv_in)
+         ELSEIF ( kt > 0 ) THEN
+            CALL sherr( NF90_GET_VAR(idx_f, idx_v, X, start=(/1,1,kt/), count=(/lx,ly,1/)), &
+               &      crtn,cf_in,cv_in)
+         END IF
+
+      ELSEIF ( kz > 0 ) THEN
+
+         IF ( kt == 0 ) THEN
+            CALL sherr( NF90_GET_VAR(idx_f, idx_v, X, start=(/1,1,kz/), count=(/lx,ly,1/)),  &
+               &      crtn,cf_in,cv_in)
+         ELSEIF ( kt > 0 ) THEN
+            CALL sherr( NF90_GET_VAR(idx_f, idx_v, X, start=(/1,1,kz,kt/), count=(/lx,ly,1,1/)), &
+               &      crtn,cf_in,cv_in)
+         END IF
+
+
+      END IF
+
+      ! Closing when needed:
+      IF ( (( kt == ite ).OR.( kt == 0 )).AND.(kz == kz_stop) )  THEN
+         CALL sherr( NF90_CLOSE(idx_f),  crtn,cf_in,cv_in)
+         idx_f = 0 ; idx_v = 0
+      END IF
+
+   END SUBROUTINE GETVAR_2D_R8
+
+
+
+
+
+
+
+
+   SUBROUTINE GETVAR_3D(idx_f, idx_v, cf_in, cv_in, lt, kt, X)
+
+      !!------------------------------------------------------------------
+      !! This routine extract a 3D field from a netcdf file
+      !! at a given time
+      !!
+      !! INPUT :
+      !! -------
+      !!          * idx_f    : ID of current file                  (integer)
+      !!          * idx_v    : ID of current variable              (integer)
+      !!          * cf_in      : name of the input file              (character)
+      !!          * cv_in      : name of the variable                (character)
+      !!          * lt        : time dimension of the variable     (integer)
+      !!
+      !!          * kt        : time snapshot to extract            (integer)
+      !!                      0 => input file does not have a time snapshot
+      !!                           (= old GETVAR_2D_NOTIME)
+      !!
+      !!
+      !! OUTPUT :
+      !! --------
+      !!          * X         : 3D array contening the variable     (real)
+      !!
+      !!------------------------------------------------------------------------
+
+      INTEGER,                    INTENT(inout) :: idx_f, idx_v
+      CHARACTER(len=*),           INTENT(in)    :: cf_in, cv_in
+      INTEGER,                    INTENT(in)    :: lt, kt
+      REAL(4), DIMENSION (:,:,:), INTENT(out)   :: X
+
+      INTEGER ::  &
+         & lx,  &        ! x dimension of the variable        (integer)
+         & ly,  &        ! y dimension of the variable        (integer)
+         & lz        ! z dimension of the variable        (integer)
+
+      crtn = 'GETVAR_3D'
+
+      lx = size(X,1)
+      ly = size(X,2)
+      lz = size(X,3)
+
+      IF ( kt <= 1 ) THEN   ! Opening file and defining variable :
+         CALL sherr( NF90_OPEN(cf_in, NF90_NOWRITE,  idx_f),  crtn,cf_in,cv_in)
+         CALL sherr( NF90_INQ_VARID(idx_f, cv_in, idx_v),  crtn,cf_in,cv_in)
+      END IF
+
+      IF ( kt == 0 ) THEN
+         CALL sherr( NF90_GET_VAR(idx_f, idx_v, X, start=(/1,1,1/), count=(/lx,ly,lz/)), &
+            &      crtn,cf_in,cv_in)
+      ELSEIF ( kt > 0 ) THEN
+         CALL sherr( NF90_GET_VAR(idx_f, idx_v, X, start=(/1,1,1,kt/), count=(/lx,ly,lz,1/)), &
+            &      crtn,cf_in,cv_in)
+      END IF
+
+      IF (( kt == lt ).or.( kt == 0 ))  THEN
+         CALL sherr( NF90_CLOSE(idx_f),  crtn,cf_in,cv_in)
+         idx_f = 0 ; idx_v = 0
+      END IF
+
+   END SUBROUTINE GETVAR_3D
+
+
+
+
+   SUBROUTINE GETMASK_2D(cf_in, cv_in, IX, jlev)
+
+      !!-----------------------------------------------------------------------
+      !!  Get mask (variable 'cv_in') from a netcdf file.
+      !! - mask is stored in integer array IX
+      !!
+      !! INPUT :
+      !! -------
+      !!          * cf_in      : name of the input file          (character)
+      !!          * cv_in      : name of mask variable           (character)
+      !!
+      !!          * jlev      : level to get (0 if no levels) |OPTIONAL|     (integer)
+      !!
+      !! OUTPUT :
+      !! --------
+      !!          * IX        :  2D array contening mask       (integer)
+      !!
+      !!------------------------------------------------------------------------
+
+      CHARACTER(len=*),        INTENT(in)  :: cf_in, cv_in
+      INTEGER, OPTIONAL,       INTENT(in)  :: jlev
+      INTEGER(2), DIMENSION(:,:), INTENT(out) :: IX
+
+      INTEGER :: &
+         & lx, &    ! x dimension of the mask
+         & ly       ! y dimension of the mask
+
+      INTEGER :: nx, ny, nk, nt, icz
+
+      crtn = 'GETMASK_2D'
+
+      lx = size(IX,1)
+      ly = size(IX,2)
+
+      icz = 1 ! getting mask at level 1 for default
+
+      IF ( present(jlev) ) THEN
+         IF ( jlev > 0 ) THEN
+            icz = jlev ; WRITE(6,*) 'Getting mask at level', icz
+         ELSE
+            CALL print_err(crtn, 'you cannot specify a level jlev <= 0')
+         END IF
+      END IF
+
+      CALL DIMS(cf_in, cv_in, nx, ny, nk, nt)
+      
+      IF ( (nx /= lx).OR.(ny /= ly) ) THEN
+         PRINT *, ' field: nx,ny / mask lx,ly =>', nx,ny, '/', lx,ly
+         CALL print_err(crtn, 'data and mask file dont have same horizontal dimensions')
+      END IF
+
+
+
+      !!    Opening MASK netcdf file
+      CALL sherr( NF90_OPEN(cf_in, NF90_NOWRITE, id_f),  crtn,cf_in,cv_in)
+      CALL sherr( NF90_INQ_VARID(id_f, trim(cv_in), id_v),  crtn,cf_in,cv_in)
+
+
+      IF ( nk > 0 ) THEN
+
+         !! Mask is 3D
+         !! ~~~~~~~~~~
+
+         IF ( .NOT. present(jlev) ) THEN
+            WRITE(6,*) trim(crtn),': WARNING => mask is 3D, should specify a level to extract, defaulting to 1st level!'
+         END IF
+
+         !!  3D+T
+         IF ( nt > 0 ) THEN
+            CALL sherr( NF90_GET_VAR(id_f, id_v, IX, start=(/1,1,icz,1/), count=(/nx,ny,1,1/)),  &
+               &      crtn,cf_in,cv_in)
+         ELSE
+            !! 3D
+            CALL sherr( NF90_GET_VAR(id_f, id_v, IX, start=(/1,1,icz/), count=(/nx,ny,1/)), &
+               &      crtn,cf_in,cv_in)
+         END IF
+
+      ELSE
+
+         !! Mask is 2D
+         !! ~~~~~~~~~~
+         IF ( present(jlev) ) CALL print_err(crtn, 'you want mask at a given level but mask is 2D')
+
+         IF ( nt > 0 ) THEN
+            !!  2D+T
+            CALL sherr( NF90_GET_VAR(id_f, id_v, IX, start=(/1,1,1/), count=(/nx,ny,1/)), crtn,cf_in,cv_in)
+         ELSE
+            !! 2D
+            CALL sherr( NF90_GET_VAR(id_f, id_v, IX),  crtn,cf_in,cv_in)
+         END IF
+
+
+      END IF
+
+      CALL sherr( NF90_CLOSE(id_f),  crtn,cf_in,cv_in)
+
+   END SUBROUTINE GETMASK_2D
+
+
+
+
+
+   SUBROUTINE GETMASK_3D(cf_in, cv_in, IX)
+
+      !!-----------------------------------------------------------------------
+      !!  Get mask (variable 'cv_in') from a netcdf file.
+      !! - mask is stored in integer array IX
+      !!
+      !! INPUT :
+      !! -------
+      !!          * cf_in      : name of the input file          (character)
+      !!          * cv_in      : name of mask variable           (character)
+      !!
+      !! OUTPUT :
+      !! --------
+      !!          * IX        :  3D array contening mask       (integer)
+      !!
+      !!  Author :            Laurent Brodeau
+      !!  --------
+      !!------------------------------------------------------------------------
+
+      CHARACTER(len=*),          INTENT(in)  :: cf_in, cv_in
+      INTEGER(2), DIMENSION(:,:,:), INTENT(out) :: IX
+
+      INTEGER :: &
+         & lx, &    ! x dimension of the mask
+         & ly, &    ! y dimension of the mask
+         & lz       ! z dimension of the mask
+
+      INTEGER :: nx, ny, nk, nt
+
+      crtn = 'GETMASK_3D'
+
+      lx = size(IX,1)
+      ly = size(IX,2)
+      lz = size(IX,3)
+
+      CALL DIMS(cf_in, cv_in, nx, ny, nk, nt)
+
+      IF ( nk < 1 ) THEN
+         WRITE(6,*) 'mask 3D file => ', trim(cf_in)
+         WRITE(6,*) 'mask 3D name => ', trim(cv_in)
+         CALL print_err(crtn, 'mask is not 3D')
+      END IF
+
+      IF ( (nx /= lx).OR.(ny /= ly).OR.(nk /= lz) ) THEN
+         PRINT *, ' field: nx,ny,nk / mask lx,ly,lz =>', nx,ny,nk,'/',lx,ly,lz
+         CALL print_err(crtn, 'data and mask file dont have the same shape')
+      END IF
+      
+      !!    Opening MASK netcdf file
+      CALL sherr( NF90_OPEN(cf_in, NF90_NOWRITE, id_f),     crtn,cf_in,cv_in)
+      CALL sherr( NF90_INQ_VARID(id_f, trim(cv_in), id_v),  crtn,cf_in,cv_in)
+
+      IF ( nt > 0 ) THEN
+         !! 3D+T
+         CALL sherr( NF90_GET_VAR(id_f, id_v, IX, start=(/1,1,1,1/), count=(/nx,ny,nk,1/)), &
+            &      crtn,cf_in,cv_in)
+
+      ELSE
+         !! 3D
+         CALL sherr( NF90_GET_VAR(id_f, id_v, IX),  crtn,cf_in,cv_in)
+      END IF
+
+      CALL sherr( NF90_CLOSE(id_f),  crtn,cf_in,cv_in)
+
+   END SUBROUTINE GETMASK_3D
+
+
+
+
+
+   SUBROUTINE P2D_T(idx_f, idx_v, lt, lct, xlon, xlat, vtime, x2d, cf_in, &
+      &           cv_lo, cv_la, cv_t, cv_in, cunit, cln, vflag, cun_t, lpack)
+      !!
+      !! INPUT :
+      !! -------
+      !!        idx_f = ID of the file (takes its value on the first call)
+      !!        idx_v = ID of the variable //
+      !!        lt    = t dimension of array to plot              [integer]
+      !!        lct   = current time step                         [integer]
+      !!        xlon  = 2D array of longitude  (nx,ny) or (nx,1)  [double]
+      !!        xlat  = 2D array of latitude   (nx,ny) or (ny,1)  [double]
+      !!        vtime  = time array                               [array 1D]
+      !!        x2d = 2D snap of 2D+T array at time jt to write   [real]
+      !!        cf_in  = name of the output file                  [character]
+      !!        cv_lo = name of longitude                         [character]
+      !!        cv_la = name of latitude                          [character]
+      !!        cv_t = name of time                               [character]
+      !!        cv_in  = name of the variable                     [character]
+      !!        cunit  = unit for treated variable                [character]
+      !!        cln = long-name for treated variable              [character]
+      !!        vflag = flag value or "0."                        [real]
+      !!
+      !!        cun_t = unit for time                 |OPTIONAL|  [character]
+      !!        lpack = wether to pack (to short)     |OPTIONAL|  [logical]
+      !!
+      !!--------------------------------------------------------------------------
+      !!
+      INTEGER,                    INTENT(inout) :: idx_f, idx_v
+      INTEGER,                    INTENT(in)    :: lt, lct
+      REAL(8), DIMENSION(:,:),    INTENT(in)    :: xlat, xlon
+      REAL(4), DIMENSION(:,:),    INTENT(in)    :: x2d
+      REAL(8), DIMENSION(lt),     INTENT(in)    :: vtime
+      CHARACTER(len=*),           INTENT(in)    :: cf_in, cv_lo, cv_la, cv_t, cv_in, cunit, cln
+      REAL(4),                    INTENT(in)    :: vflag
+      CHARACTER(len=*), OPTIONAL, INTENT(in)    :: cun_t
+      LOGICAL,          OPTIONAL, INTENT(in)    :: lpack
+      !!
+      INTEGER          :: lx, ly
+      REAL(4)          :: dr
+      LOGICAL          :: lp = .FALSE.
+      !!
+      INTEGER(2), DIMENSION(:,:), ALLOCATABLE :: ix2d
+      !!
+      !!
+      crtn = 'P2D_T'
+      !!
+      !! About dimensions of xlon, xlat and x2d:
+      CALL ctest_coor(xlon, xlat, x2d, cdt)
+      lx = size(x2d,1) ; ly = size(x2d,2)
+      !!
+      IF ( present(lpack) ) THEN
+         IF ( lpack ) lp = .TRUE.
+      END IF
+      !!
+      !!
+      IF ( lct == 1 ) THEN
+         !!
+         IF ( vflag /= 0.) THEN
+            rmin =  1.E6 ; rmax = -1.E6
+            DO ji=1, lx
+               DO jj=1, ly
+                  IF ((x2d(ji,jj) <= rmin).and.(x2d(ji,jj) /= vflag)) rmin = x2d(ji,jj)
+                  IF ((x2d(ji,jj) >= rmax).and.(x2d(ji,jj) /= vflag)) rmax = x2d(ji,jj)
+               END DO
+            END DO
+         ELSE
+            rmin = minval(x2d) ; rmax = maxval(x2d)
+         END IF
+         !!
+         dr = (rmax - rmin)/10.0 ; rmin = rmin - dr ; rmax = rmax + dr
+         !!
+         IF ( lp ) THEN
+            ! following: http://www.unidata.ucar.edu/software/netcdf/docs/BestPractices.html
+            ! => to short (2bytes = 16 bits)
+            scale_f = (rmax - rmin)/65535. ! 65536 = 2^16 - 1
+            !add_off = rmin + 128.*scale_f
+            add_off = rmin + 32768.*scale_f       ! 32768 = 2^(16-1)
+         END IF
+         !!
+         cu = 'unknown'
+         IF ( present(cun_t) ) cu = trim(cun_t)
+         !!
+      END IF ! lct == 1
+      !!
+      !!
+      IF ( lp ) THEN
+         ALLOCATE ( ix2d(lx,ly) )
+         !ix2d = INT( (x2d -add_off)/scale_f , 2)
+         ! following: http://www.unidata.ucar.edu/software/netcdf/docs/BestPractices.html :
+         ix2d = NINT( (x2d - add_off)/scale_f )
+         WHERE(x2d == vflag) ix2d = imv
+      END IF
+      !!
+      !!
+      !!
+      IF ( lct == 1 ) THEN
+         !!
+         !!
+         vextrema(1,:) = (/minval(xlon),maxval(xlon)/); vextrema(2,:) = (/minval(xlat),maxval(xlat)/)
+         vextrema(3,:) = (/minval(vtime),maxval(vtime)/)
+         !!
+         !! Opening mesh file for grid quest :
+         !! ----------------------------------
+         !!
+         !!           CREATE NETCDF OUTPUT FILE :
+         CALL sherr( NF90_CREATE(cf_in, NF90_CLOBBER, idx_f),  crtn,cf_in,cv_in)
+         !!
+         CALL prepare_nc(idx_f, cdt, lx, ly, cv_lo, cv_la, cv_t, cu, vextrema, &
+            &          id_x, id_y, id_t, id_lo, id_la, id_tim, crtn,cf_in,cv_in)
+         !!
+         !! Variable
+         IF ( lp ) THEN
+            CALL sherr( NF90_DEF_VAR(idx_f, trim(cv_in), NF90_SHORT, (/id_x,id_y,id_t/), idx_v),  crtn,cf_in,cv_in)
+         ELSE
+            CALL sherr( NF90_DEF_VAR(idx_f, trim(cv_in), NF90_FLOAT,(/id_x,id_y,id_t/), idx_v),  crtn,cf_in,cv_in)
+         END IF
+         !!
+         !!
+         !!  VARIABLE ATTRIBUTES
+         !!
+         !! Long name
+         CALL sherr( NF90_PUT_ATT(idx_f, idx_v, 'long_name', trim(cln)),  crtn,cf_in,cv_in)
+         !!
+         !! Units
+         CALL sherr( NF90_PUT_ATT(idx_f, idx_v, 'units', trim(cunit) ),   crtn,cf_in,cv_in)
+         !!
+         !!
+         IF ( lp ) THEN
+            !!
+            CALL sherr( NF90_PUT_ATT(idx_f, idx_v, 'scale_factor', scale_f),  crtn,cf_in,cv_in)
+            CALL sherr( NF90_PUT_ATT(idx_f, idx_v, 'add_offset',   add_off),  crtn,cf_in,cv_in)
+            !!
+            IF ( vflag /= 0.) &  ! Missing value
+               & CALL sherr( NF90_PUT_ATT(idx_f, idx_v,'_FillValue', imv),  crtn,cf_in,cv_in)
+            !!
+         ELSE
+            IF ( vflag /= 0.) &   ! Missing value
+               & CALL sherr( NF90_PUT_ATT(idx_f, idx_v,'_FillValue',vflag),  crtn,cf_in,cv_in)
+         END IF
+         !!
+         CALL sherr( NF90_PUT_ATT(idx_f, idx_v,'valid_range', (/rmin,rmax/)),  crtn,cf_in,cv_in)
+         !!
+         !!
+         !!
+         !! Global attributes
+         CALL sherr( NF90_PUT_ATT(idx_f, NF90_GLOBAL, 'About', trim(cabout)),  crtn,cf_in,cv_in)
+         !!
+         !!
+         !!           END OF DEFINITION
+         !!           -----------------
+         CALL sherr( NF90_ENDDEF(idx_f),  crtn,cf_in,cv_in)
+         !!
+         !!
+         !!          WRITE COORDINATES
+         !!          -----------------
+         !!       Write longitude variable :
+         CALL sherr( NF90_PUT_VAR(idx_f, id_lo, xlon),  crtn,cf_in,cv_in)
+         !!
+         !!       Write latitude variable :
+         CALL sherr( NF90_PUT_VAR(idx_f, id_la, xlat),  crtn,cf_in,cv_in)
+         !!
+         !!       Write time variable :
+         CALL sherr( NF90_PUT_VAR(idx_f, id_tim, vtime),  crtn,cf_in,cv_in)
+         !!
+      END IF
+      !!
+      !!               WRITE VARIABLE
+      IF ( lp ) THEN
+         CALL sherr( NF90_PUT_VAR(idx_f, idx_v, ix2d, start=(/1,1,lct/), count=(/lx,ly,1/)),  crtn,cf_in,cv_in)
+      ELSE
+         CALL sherr( NF90_PUT_VAR(idx_f, idx_v, x2d,  start=(/1,1,lct/), count=(/lx,ly,1/)),  crtn,cf_in,cv_in)
+      END IF
+      !!
+      IF ( lp ) DEALLOCATE( ix2d )
+      !!
+      IF ( lct == lt ) CALL sherr( NF90_CLOSE(idx_f),  crtn,cf_in,cv_in)
+      !!
+   END SUBROUTINE P2D_T
+
+
+
+
+
+   SUBROUTINE P3D_T(idx_f, idx_v, lt, lct, xlon, xlat, vdpth, vtime, x3d, cf_in, &
+      &           cv_lo, cv_la, cv_z, cv_t, cv_in, cunit, cln, vflag, &
+      &           cun_t, lpack, cun_z)
+
+      !! INPUT :
+      !! -------
+      !!        idx_f = ID of the file (takes its value on the first call)
+      !!        idx_v = ID of the variable //
+      !!        lt    = t dimension of array to plot              [integer]
+      !!        lct   = current time step                         [integer]
+      !!        xlon  = 2D array of longitude  (nx,ny) or (nx,1)  [double]
+      !!        xlat  = 2D array of latitude   (nx,ny) or (ny,1)  [double]
+      !!        vdpth = depth array                               [array 1D double]
+      !!        vtime  = time array                               [array 1D double]
+      !!        x3d = 3D snap of 3D+T array at time jt to write   [real]
+      !!        cf_in  = name of the output file                  [character]
+      !!        cv_lo = name of longitude                         [character]
+      !!        cv_la = name of latitude                          [character]
+      !!        cv_z = name of depth                              [character]
+      !!        cv_t = name of time                               [character]
+      !!        cv_in  = name of the variable                     [character]
+      !!        cunit  = unit for treated variable                [character]
+      !!        cln = long-name for treated variable              [character]
+      !!        vflag = flag value or "0."                        [real]
+      !!
+      !!        cun_t = unit for time                 |OPTIONAL|  [character]
+      !!        lpack = wether to pack (to short)     |OPTIONAL|  [logical
+      !!        cun_z = unit for depth                |OPTIONAL|  [character]
+      !!
+      !!--------------------------------------------------------------------------
+
+      INTEGER,                    INTENT(inout) :: idx_f, idx_v
+      INTEGER,                    INTENT(in)    :: lt, lct
+      REAL(4), DIMENSION(:,:,:),  INTENT(in)    :: x3d
+      REAL(8), DIMENSION(:,:),    INTENT(in)    :: xlat, xlon
+      REAL(8), DIMENSION(:),      INTENT(in)    :: vdpth
+      REAL(8), DIMENSION(lt),     INTENT(in)    :: vtime
+      CHARACTER(len=*),           INTENT(in)    :: cf_in, cv_lo, cv_la, cv_z, cv_t, cv_in, cunit, cln
+      REAL(4),                    INTENT(in)    :: vflag
+      CHARACTER(len=*), OPTIONAL, INTENT(in)    :: cun_t, cun_z
+      LOGICAL,          OPTIONAL, INTENT(in)    :: lpack
+      !!
+      INTEGER          :: lx, ly, lz
+      REAL(4)          :: dr
+      LOGICAL          :: lp = .FALSE.
+      !!
+      INTEGER(2), DIMENSION(:,:,:), ALLOCATABLE :: ix3d
+      !!
+      !!
+      crtn = 'P3D_T'
+      !!
+      !! About dimensions of xlon, xlat, vdpth and x3d:
+      CALL ctest_coor(xlon, xlat, x3d(:,:,1), cdt)
+      lx = size(x3d,1) ; ly = size(x3d,2) ; lz = size(vdpth)
+      IF ( size(x3d,3) /= lz ) CALL print_err(crtn, 'depth array do not match data')
+      !!
+      IF ( present(lpack) ) THEN
+         IF ( lpack ) lp = .TRUE.
+      END IF
+      !!
+      !!
+      IF ( lct == 1 ) THEN
+         !!
+         IF ( vflag /= 0.) THEN
+            rmin =  1.E6 ; rmax = -1.E6
+            DO ji=1, lx
+               DO jj=1, ly
+                  DO jk=1, lz
+                     IF ((x3d(ji,jj,jk) <= rmin).and.(x3d(ji,jj,jk) /= vflag)) rmin = x3d(ji,jj,jk)
+                     IF ((x3d(ji,jj,jk) >= rmax).and.(x3d(ji,jj,jk) /= vflag)) rmax = x3d(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+         ELSE
+            rmin = minval(x3d) ; rmax = maxval(x3d)
+         END IF
+         !!
+         dr = (rmax - rmin)/10.0 ; rmin = rmin - dr ; rmax = rmax + dr
+         !!
+         IF ( lp ) THEN
+            ! following: http://www.unidata.ucar.edu/software/netcdf/docs/BestPractices.html
+            scale_f = (rmax - rmin)/65535. ! 65536 = 2^16 - 1
+            !add_off = rmin + 128.*scale_f
+            add_off = rmin + 32768.*scale_f       ! 32768 = 2^(16-1)
+         END IF
+         !!
+         cu = 'unknown'
+         IF ( present(cun_t) ) cu = cun_t
+         !!
+      END IF ! lct == 1
+      !!
+      !!
+      IF ( lp ) THEN
+         ALLOCATE ( ix3d(lx,ly,lz) )
+         !ix3d = INT( (x3d -add_off)/scale_f , 2)
+         ! following: http://www.unidata.ucar.edu/software/netcdf/docs/BestPractices.html :
+         ix3d = NINT( (x3d - add_off)/scale_f )
+         WHERE(x3d == vflag) ix3d = imv
+      END IF
+      !!
+      !!
+      !!
+      IF ( lct == 1 ) THEN
+         !!
+         vextrema(1,:) = (/minval(xlon),maxval(xlon)/); vextrema(2,:) = (/minval(xlat),maxval(xlat)/)
+         vextrema(3,:) = (/minval(vtime),maxval(vtime)/)
+         !!
+         !! Opening mesh file for grid quest :
+         !! ----------------------------------
+         !!
+         !!           CREATE NETCDF OUTPUT FILE :
+         CALL sherr( NF90_CREATE(cf_in, NF90_CLOBBER, idx_f),  crtn,cf_in,cv_in)
+         !!
+         CALL prepare_nc(idx_f, cdt, lx, ly, cv_lo, cv_la, cv_t, cu, vextrema, &
+            &          id_x, id_y, id_t, id_lo, id_la, id_tim, crtn,cf_in,cv_in)
+         !!
+         CALL sherr( NF90_DEF_DIM(idx_f, trim(cv_z), lz, id_z),  crtn,cf_in,cv_in)
+
+         CALL sherr( NF90_DEF_VAR(idx_f, trim(cv_z), NF90_DOUBLE, id_z,id_dpt),  crtn,cf_in,cv_in)
+         cu = 'unknown'
+         IF ( present(cun_z) ) cu = cun_z
+         CALL sherr( NF90_PUT_ATT(idx_f, id_dpt, 'units',     trim(cu)),       crtn,cf_in,cv_in)
+         CALL sherr( NF90_PUT_ATT(idx_f, id_dpt, 'valid_min', minval(vdpth)),  crtn,cf_in,cv_in)
+         CALL sherr( NF90_PUT_ATT(idx_f, id_dpt, 'valid_max', maxval(vdpth)),  crtn,cf_in,cv_in)
+         !!
+         !!
+         !! Variable
+         IF ( lp ) THEN
+            CALL sherr( NF90_DEF_VAR(idx_f, trim(cv_in), NF90_SHORT, (/id_x,id_y,id_z,id_t/), idx_v),  crtn,cf_in,cv_in)
+         ELSE
+            CALL sherr( NF90_DEF_VAR(idx_f, trim(cv_in), NF90_FLOAT, (/id_x,id_y,id_z,id_t/), idx_v),  crtn,cf_in,cv_in)
+         END IF
+         !!
+         !!
+         !!  VARIABLE ATTRIBUTES
+         CALL sherr( NF90_PUT_ATT(idx_f, idx_v, 'long_name', trim(cln)),  crtn,cf_in,cv_in)
+         CALL sherr( NF90_PUT_ATT(idx_f, idx_v, 'units', trim(cunit) ),   crtn,cf_in,cv_in)
+         !!
+         IF ( lp ) THEN
+            CALL sherr( NF90_PUT_ATT(idx_f, idx_v, 'scale_factor', scale_f),  crtn,cf_in,cv_in)
+            CALL sherr( NF90_PUT_ATT(idx_f, idx_v, 'add_offset',   add_off),  crtn,cf_in,cv_in)
+            IF ( vflag /= 0.) CALL sherr( NF90_PUT_ATT(idx_f, idx_v,'_FillValue', imv),  crtn,cf_in,cv_in)
+         ELSE
+            IF ( vflag /= 0.) CALL sherr( NF90_PUT_ATT(idx_f, idx_v,'_FillValue',vflag),  crtn,cf_in,cv_in)
+         END IF
+         !!
+         CALL sherr( NF90_PUT_ATT(idx_f, idx_v,'valid_range', (/rmin,rmax/)),  crtn,cf_in,cv_in)
+         !!
+         !!
+         !! Global attributes
+         CALL sherr( NF90_PUT_ATT(idx_f, NF90_GLOBAL, 'About', trim(cabout)),  crtn,cf_in,cv_in)
+         !!
+         !!           END OF DEFINITION
+         CALL sherr( NF90_ENDDEF(idx_f),  crtn,cf_in,cv_in)
+         !!
+         !!
+         !!
+         !!       Write longitude variable :
+         CALL sherr( NF90_PUT_VAR(idx_f, id_lo, xlon),  crtn,cf_in,cv_in)
+         !!
+         !!       Write latitude variable :
+         CALL sherr( NF90_PUT_VAR(idx_f, id_la, xlat),  crtn,cf_in,cv_in)
+         !!
+         !!       Write depth variable :
+         CALL sherr( NF90_PUT_VAR(idx_f, id_dpt, vdpth),  crtn,cf_in,cv_in)
+         !!
+         !!       Write time variable :
+         CALL sherr( NF90_PUT_VAR(idx_f, id_tim, vtime),  crtn,cf_in,cv_in)
+         !!
+      END IF
+      !!
+      !!
+      !!                WRITE VARIABLE
+      IF ( lp ) THEN
+         CALL sherr( NF90_PUT_VAR(idx_f, idx_v, ix3d, start=(/1,1,1,lct/), count=(/lx,ly,lz,1/)),  crtn,cf_in,cv_in)
+      ELSE
+         CALL sherr( NF90_PUT_VAR(idx_f, idx_v,  x3d, start=(/1,1,1,lct/), count=(/lx,ly,lz,1/)),  crtn,cf_in,cv_in)
+      END IF
+      !!
+      IF ( lp ) DEALLOCATE( ix3d )
+      !!
+      IF ( lct == lt ) CALL sherr( NF90_CLOSE(idx_f),  crtn,cf_in,cv_in)
+      !!
+      !!
+   END SUBROUTINE P3D_T
+   !!
+   !!
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+   SUBROUTINE P3D_T_4V(idx_f, idx_v1, idx_v2, idx_v3, idx_v4, lt, lct, &
+      &                xlon, xlat, vdpth, vtime, x3d1, x3d2, x3d3, x3d4, &
+      &                cf_in, cv_lo, cv_la, cv_z, cv_t, &
+      &                cv_in1, cv_in2, cv_in3, cv_in4, vflag, &
+      &                cun_t, cun_z)
+      
+      !! INPUT :
+      !! -------
+      !!        idx_f = ID of the file (takes its value on the first call)
+      !!        idx_v = ID of the variable //
+      !!        lt    = t dimension of array to plot              [integer]
+      !!        lct   = current time step                         [integer]
+      !!        xlon  = 2D array of longitude  (nx,ny) or (nx,1)  [double]
+      !!        xlat  = 2D array of latitude   (nx,ny) or (ny,1)  [double]
+      !!        vdpth = depth array                               [array 1D double]
+      !!        vtime  = time array                               [array 1D double]
+      !!        x3d = 3D snap of 3D+T array at time jt to write   [real]
+      !!        cf_in  = name of the output file                  [character]
+      !!        cv_lo = name of longitude                         [character]
+      !!        cv_la = name of latitude                          [character]
+      !!        cv_z = name of depth                              [character]
+      !!        cv_t = name of time                               [character]
+      !!        cv_in  = name of the variable                     [character]
+      !!        vflag = flag value or "0."                        [real]
+      !!
+      !!        cun_t = unit for time                 |OPTIONAL|  [character]
+      !!        cun_z = unit for depth                |OPTIONAL|  [character]
+      !!
+      !!--------------------------------------------------------------------------
+
+      INTEGER,                    INTENT(inout) :: idx_f, idx_v1, idx_v2, idx_v3, idx_v4
+      INTEGER,                    INTENT(in)    :: lt, lct
+      REAL(4), DIMENSION(:,:,:),  INTENT(in)    :: x3d1, x3d2, x3d3, x3d4
+      REAL(4), DIMENSION(:,:),    INTENT(in)    :: xlat, xlon
+      REAL(4), DIMENSION(:),      INTENT(in)    :: vdpth
+      REAL(8), DIMENSION(lt),     INTENT(in)    :: vtime
+      CHARACTER(len=*),           INTENT(in)    :: cf_in, cv_lo, cv_la, cv_z, cv_t, cv_in1, cv_in2, cv_in3, cv_in4
+      REAL(4),                    INTENT(in)    :: vflag
+      CHARACTER(len=*), OPTIONAL, INTENT(in)    :: cun_t, cun_z
+      !!
+      INTEGER          :: lx, ly, lz
+      REAL(4)          :: dr
+      !!
+      !!
+      !!
+      crtn = 'P3D_T_4V'
+      !!
+      !! About dimensions of xlon, xlat, vdpth and x3d1:
+      CALL ctest_coor(REAL(xlon,8), REAL(xlat,8), x3d1(:,:,1), cdt)
+      lx = size(x3d1,1) ; ly = size(x3d1,2) ; lz = size(vdpth)
+      IF ( size(x3d1,3) /= lz ) CALL print_err(crtn, 'depth array do not match data')
+      !!
+      !!
+      !!
+      !!
+      IF ( lct == 1 ) THEN
+         !!
+         cu = 'unknown'
+         IF ( present(cun_t) ) cu = cun_t
+         !!
+         vextrema(1,:) = (/minval(xlon),maxval(xlon)/); vextrema(2,:) = (/minval(xlat),maxval(xlat)/)
+         vextrema(3,:) = (/minval(vtime),maxval(vtime)/)
+         !!
+         !! Opening mesh file for grid quest :
+         !! ----------------------------------
+         !!
+         !!           CREATE NETCDF OUTPUT FILE :
+         CALL sherr( NF90_CREATE(cf_in, NF90_CLOBBER, idx_f),  crtn,cf_in,cv_in1)
+         !!
+         CALL prepare_nc(idx_f, cdt, lx, ly, cv_lo, cv_la, cv_t, cu, vextrema, &
+            &          id_x, id_y, id_t, id_lo, id_la, id_tim, crtn,cf_in,cv_in1)
+         !!
+         CALL sherr( NF90_DEF_DIM(idx_f, trim(cv_z), lz, id_z),  crtn,cf_in,cv_in1)
+
+         CALL sherr( NF90_DEF_VAR(idx_f, trim(cv_z), NF90_DOUBLE, id_z,id_dpt),  crtn,cf_in,cv_in1)
+         cu = 'unknown'
+         IF ( present(cun_z) ) cu = cun_z
+         CALL sherr( NF90_PUT_ATT(idx_f, id_dpt, 'units',     trim(cu)),       crtn,cf_in,cv_in1)
+         CALL sherr( NF90_PUT_ATT(idx_f, id_dpt, 'valid_min', minval(vdpth)),  crtn,cf_in,cv_in1)
+         CALL sherr( NF90_PUT_ATT(idx_f, id_dpt, 'valid_max', maxval(vdpth)),  crtn,cf_in,cv_in1)
+         !!
+         !!
+         !! Variables
+         CALL sherr( NF90_DEF_VAR(idx_f, trim(cv_in1), NF90_FLOAT, (/id_x,id_y,id_z,id_t/), idx_v1),  crtn,cf_in,cv_in1)
+         CALL sherr( NF90_DEF_VAR(idx_f, trim(cv_in2), NF90_FLOAT, (/id_x,id_y,id_z,id_t/), idx_v2),  crtn,cf_in,cv_in2)
+         CALL sherr( NF90_DEF_VAR(idx_f, trim(cv_in3), NF90_FLOAT, (/id_x,id_y,id_z,id_t/), idx_v3),  crtn,cf_in,cv_in3)
+         CALL sherr( NF90_DEF_VAR(idx_f, trim(cv_in4), NF90_FLOAT, (/id_x,id_y,id_z,id_t/), idx_v4),  crtn,cf_in,cv_in4)
+         !!
+         !!
+         !!  VARIABLE ATTRIBUTES
+         !!
+         IF ( vflag /= 0.) THEN
+            CALL sherr( NF90_PUT_ATT(idx_f, idx_v1,'_FillValue',vflag),  crtn,cf_in,cv_in1)
+            CALL sherr( NF90_PUT_ATT(idx_f, idx_v2,'_FillValue',vflag),  crtn,cf_in,cv_in2)
+            CALL sherr( NF90_PUT_ATT(idx_f, idx_v3,'_FillValue',vflag),  crtn,cf_in,cv_in3)
+            CALL sherr( NF90_PUT_ATT(idx_f, idx_v4,'_FillValue',vflag),  crtn,cf_in,cv_in4)
+         END IF
+         !!
+         !!
+         !! Global attributes
+         CALL sherr( NF90_PUT_ATT(idx_f, NF90_GLOBAL, 'About', trim(cabout)),  crtn,cf_in,cv_in1)
+         !!
+         !!           END OF DEFINITION
+         CALL sherr( NF90_ENDDEF(idx_f),  crtn,cf_in,cv_in1)
+         !!
+         !!
+         !!
+         !!       Write longitude variable :
+         CALL sherr( NF90_PUT_VAR(idx_f, id_lo, xlon),  crtn,cf_in,cv_in1)
+         !!
+         !!       Write latitude variable :
+         CALL sherr( NF90_PUT_VAR(idx_f, id_la, xlat),  crtn,cf_in,cv_in1)
+         !!
+         !!       Write depth variable :
+         CALL sherr( NF90_PUT_VAR(idx_f, id_dpt, vdpth),  crtn,cf_in,cv_in1)
+         !!
+         !!       Write time variable :
+         CALL sherr( NF90_PUT_VAR(idx_f, id_tim, vtime),  crtn,cf_in,cv_in1)
+         !!
+      END IF
+      !!
+      !!
+      !!                WRITE VARIABLE
+      CALL sherr( NF90_PUT_VAR(idx_f, idx_v1,  x3d1, start=(/1,1,1,lct/), count=(/lx,ly,lz,1/)),  crtn,cf_in,cv_in1)
+      CALL sherr( NF90_PUT_VAR(idx_f, idx_v2,  x3d2, start=(/1,1,1,lct/), count=(/lx,ly,lz,1/)),  crtn,cf_in,cv_in2)
+      CALL sherr( NF90_PUT_VAR(idx_f, idx_v3,  x3d3, start=(/1,1,1,lct/), count=(/lx,ly,lz,1/)),  crtn,cf_in,cv_in3)
+      CALL sherr( NF90_PUT_VAR(idx_f, idx_v4,  x3d4, start=(/1,1,1,lct/), count=(/lx,ly,lz,1/)),  crtn,cf_in,cv_in4)
+      !!
+      IF ( lct == lt ) CALL sherr( NF90_CLOSE(idx_f),  crtn,cf_in,cv_in1)
+      !!
+      !!
+   END SUBROUTINE P3D_T_4V
+   !!
+   !!
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+   !!
+   !!
+   SUBROUTINE CHECK_4_MISS(cf_in, cv_in, lmv, rmissval, cmiss)
+      !!
+      !! o This routine looks for the presence of a missing value attribute
+      !!   of variable cv_in into file cf_in
+      !!
+      !! INPUT :
+      !! -------
+      !!         * cv_in    = variable                                [character]
+      !!         * cf_in    = treated file                              [character]
+      !!
+      !! OUTPUT :
+      !! --------
+      !!         * imiss    = 0 -> no missing value, 1 -> missing value found   [integer]
+      !!         * rmissval = value of missing value                          [real]
+      !!         * [cmiss]  = name of the missing value arg. |OPTIONAL|  [character]
+      !!
+      !! Author : L. BRODEAU, december 2008
+      !!
+      !!----------------------------------------------------------------------------
+      !!
+      CHARACTER(len=*), INTENT(in)  :: cf_in, cv_in
+      !!
+      LOGICAL,            INTENT(out) :: lmv
+      REAL(4),         INTENT(out) :: rmissval
+      !!
+      CHARACTER(len=*) , OPTIONAL, INTENT(in)  :: cmiss
+      !!
+      INTEGER :: lx, ly, kz, kt, ierr
+      !!
+      crtn = 'CHECK_4_MISS'
+      !!
+      !!
+      !! Opening file :
+      CALL sherr( NF90_OPEN(cf_in, NF90_NOWRITE, id_f),  crtn,cf_in,cv_in)
+      !!
+      !! Chosing variable :
+      CALL sherr( NF90_INQ_VARID(id_f, cv_in, id_v),  crtn,cf_in,cv_in)
+      !!
+      !!
+      IF ( present(cmiss) ) THEN
+         ierr = NF90_GET_ATT(id_f, id_v, cmiss, rmissval)
+      ELSE
+         !! Default name for a missing value is "missing_value" :
+         ierr = NF90_GET_ATT(id_f, id_v, 'missing_value', rmissval)
+      END IF
+      !!
+      IF ( ierr == -43 ) THEN
+         lmv = .FALSE.
+         !!
+      ELSE
+         !!
+         IF (ierr ==  NF90_NOERR) THEN
+            lmv = .TRUE.
+         ELSE
+            CALL print_err(crtn, 'problem getting missing_value attribute')
+         END IF
+      END IF
+      !!
+      CALL sherr( NF90_CLOSE(id_f),  crtn,cf_in,cv_in)
+      !!
+   END SUBROUTINE CHECK_4_MISS
+   !!
+   !!
+   SUBROUTINE GET_VAR_INFO(cf_in, cv_in, cunit, clnm)
+      !!
+      !! o This routine returns the unit and longname of variable if they exist!
+      !!
+      !! INPUT :
+      !! -------
+      !!         * cv_in    = variable                                [character]
+      !!         * cf_in    = treated file                            [character]
+      !!
+      !! OUTPUT :
+      !! --------
+      !!         * cunit = unit of cv_in                              [character]
+      !!         * clnm  = name of the missing value arg.            [character]
+      !!
+      !! Author : L. BRODEAU, 2008
+      !!
+      !!----------------------------------------------------------------------------
+      !!
+      CHARACTER(len=*), INTENT(in)  :: cf_in, cv_in
+      CHARACTER(len=*) , INTENT(out) :: cunit
+      CHARACTER(len=*), INTENT(out) :: clnm
+      !!
+      CHARACTER(len=400) :: c00
+      INTEGER :: lx, ly, kz, kt, ierr
+      !!
+      crtn = 'GET_VAR_INFO'
+      !!
+      !!
+      !! Opening file :
+      CALL sherr( NF90_OPEN(cf_in, NF90_NOWRITE, id_f),  crtn,cf_in,cv_in)
+      !!
+      !! Chosing variable :
+      CALL sherr( NF90_INQ_VARID(id_f, cv_in, id_v),  crtn,cf_in,cv_in)
+      !!
+      !!
+      c00=''
+      ierr = NF90_GET_ATT(id_f, id_v, 'units', c00)
+      IF (ierr /= 0) c00 = 'UNKNOWN'
+      cunit = trim(c00) ;
+      !!
+      c00=''
+      ierr = NF90_GET_ATT(id_f, id_v, 'long_name', c00)
+      IF (ierr /= 0) c00 = 'UNKNOWN'
+      clnm = trim(c00)
+      !!
+      !!
+      CALL sherr( NF90_CLOSE(id_f),  crtn,cf_in,cv_in)
+      !!
+   END SUBROUTINE GET_VAR_INFO
+
+
+
+   SUBROUTINE PRTMASK(xmsk, cf_in, cv_in,   xlon, xlat, cv_lo, cv_la)
+      !!
+      !!-----------------------------------------------------------------------------
+      !! This routine prints an integer array of a 2D mask into a netcdf file
+      !! ( healthy minds usually agree for earth == 0, sea == 1 )
+      !!
+      !! INPUT :
+      !! -------
+      !!        xmsk  = 2D array (lx,ly) contening mask            [real4]
+      !!        cf_in  = name of the output file                   [character]
+      !!        cv_in  = name of the mask variable                 [character]
+      !! OPTIONAL :
+      !! ----------
+      !!        xlon    = longitude array
+      !!        xlat    = latitude array
+      !!        cv_lo = longitude name
+      !!        cv_la = latitude name
+      !!
+      !!------------------------------------------------------------------------------
+      !!
+      REAL(4),    DIMENSION(:,:), INTENT(in) :: xmsk
+      CHARACTER(len=*),           INTENT(in) :: cf_in, cv_in
+      !!
+      REAL(8), DIMENSION(:,:), INTENT(in), OPTIONAL :: xlon, xlat
+      CHARACTER(len=*),        INTENT(in), OPTIONAL :: cv_lo, cv_la
+      !!
+      INTEGER          :: lx, ly, i01, i02
+      !!
+      LOGICAL :: lzcoord
+      !!
+      crtn = 'PRTMASK'
+      !!
+      lx = size(xmsk,1) ; ly = size(xmsk,2)
+      !!
+      lzcoord = .FALSE.
+      !!
+      IF ( present(xlon).AND.present(xlat) ) THEN
+         IF ( present(cv_lo).AND.present(cv_la) ) THEN
+            lzcoord = .TRUE.
+            CALL ctest_coor(xlon, xlat, xmsk, cdt)
+         ELSE
+            CALL print_err(crtn, 'if you specify xlon and xlat, you must also specify cv_lo and cv_la')
+         END IF
+         vextrema(1,:) = (/minval(xlon),maxval(xlon)/); vextrema(2,:) = (/minval(xlat),maxval(xlat)/)
+      END IF
+      !!
+
+      !!
+      !!
+      !!           CREATE NETCDF OUTPUT FILE :
+      !!           ---------------------------
+      CALL sherr( NF90_CREATE(CF_IN, NF90_CLOBBER, id_f),  crtn,cf_in,cv_in)
+      !!
+      !!
+      IF ( lzcoord ) THEN
+         CALL prepare_nc(id_f, cdt, lx, ly, cv_lo, cv_la, '', '', vextrema, id_x, id_y, i01, id_lo, id_la, i02, &
+            &          crtn,cf_in,cv_in)
+      ELSE
+         CALL prepare_nc(id_f, cdt, lx, ly, '', '', '', '',       vextrema, id_x, id_y, i01, id_lo, id_la, i02, &
+            &          crtn,cf_in,cv_in)
+      END IF
+      !!
+      CALL sherr( NF90_DEF_VAR(id_f, trim(cv_in), NF90_FLOAT, (/id_x,id_y/), id_v),       crtn,cf_in,cv_in)
+      !!
+      CALL sherr( NF90_ENDDEF(id_f),  crtn,cf_in,cv_in) ! END OF DEFINITION
+      !!
+      !!
+      !!          WRITE COORDINATES
+      IF ( lzcoord ) THEN
+         CALL sherr( NF90_PUT_VAR(id_f, id_lo, xlon),  crtn,cf_in,cv_in)
+         CALL sherr( NF90_PUT_VAR(id_f, id_la, xlat),  crtn,cf_in,cv_in)
+      END IF
+      !!
+      !!          WRITE VARIABLE
+      CALL sherr( NF90_PUT_VAR(id_f, id_v, xmsk),  crtn,cf_in,cv_in)
+      !!
+      CALL sherr( NF90_CLOSE(id_f),  crtn,cf_in,cv_in)
+      !!
+      !!
+   END SUBROUTINE PRTMASK
+
+
+
+
+
+
+   SUBROUTINE PHOVMOLLER(vx, vy, x2d, cf_in, cv_in, cv_x, cv_y, cunit, cln, cuX, cuY)
+      !!
+      !!-----------------------------------------------------------------------------
+      !! This routine prints Hovmoller diagram from a 2D fiels and coordinates given as 2 vectors
+      !!
+      !! INPUT :
+      !! -------
+      !!        vx     = X array                                     [real8]
+      !!        vy     = Y array                                     [real8]
+      !!        x2d    = 2D array (lx,ly) contening mask             [real4]
+      !!        cf_in  = name of the output file                   [character]
+      !!        cv_in  = name of the mask variable                 [character]
+      !!        cf_x   = name of X coordinates                     [character]
+      !!        cf_y   = name of Y coordinates                     [character]
+      !!        cunit  = unit for treated variable                [character]
+      !!        cln = long-name for treated variable              [character]
+      !!
+      !! OPTIONAL :
+      !! ----------
+      !!        cuX  = unit X coordinate                          [character]
+      !!        cuY  = unit Y coordinate                          [character]
+      !!
+      !!------------------------------------------------------------------------------
+
+      REAL(8),    DIMENSION(:)  , INTENT(in) :: vx, vy
+      REAL(4),    DIMENSION(:,:), INTENT(in) :: x2d
+      CHARACTER(len=*),           INTENT(in) :: cf_in, cv_in, cv_x, cv_y, cunit, cln
+
+      CHARACTER(len=*), OPTIONAL, INTENT(in) :: cuX, cuY
+
+      CHARACTER(len=64) :: cuXin, cuYin
+      INTEGER :: lx, ly, i01, i02
+
+      crtn = 'PHOVMOLLER'
+
+      lx = size(x2d,1) ; ly = size(x2d,2)
+
+      cuXin = 'unknown'
+      cuYin = 'unknown'
+      IF ( present(cuX) ) cuXin = trim(cuX)
+      IF ( present(cuY) ) cuYin = trim(cuY)
+
+
+
+      vextrema(1,:) = (/minval(vx),maxval(vx)/); vextrema(2,:) = (/minval(vy),maxval(vy)/)
+
+      !!           CREATE NETCDF OUTPUT FILE :
+      CALL sherr( NF90_CREATE(CF_IN, NF90_CLOBBER, id_f),  crtn,cf_in,cv_in)
+
+      CALL prepare_nc(id_f, '1d', lx, ly, cv_x, cv_y, '', '', vextrema, id_x, id_y, i01, id_lo, id_la, i02, &
+         &          crtn,cf_in,cv_in, cu_X=trim(cuXin), cu_Y=trim(cuYin))
+
+      CALL sherr( NF90_DEF_VAR(id_f, trim(cv_in), NF90_FLOAT, (/id_x,id_y/), id_v),       crtn,cf_in,cv_in)
+
+      CALL sherr( NF90_PUT_ATT(id_f, id_v, 'long_name', trim(cln)),  crtn,cf_in,cv_in)
+      CALL sherr( NF90_PUT_ATT(id_f, id_v, 'units',  trim(cunit) ),  crtn,cf_in,cv_in)
+      !! Global attributes
+      CALL sherr( NF90_PUT_ATT(id_f, NF90_GLOBAL, 'About', trim(cabout)),  crtn,cf_in,cv_in)
+
+      CALL sherr( NF90_ENDDEF(id_f),  crtn,cf_in,cv_in) ! END OF DEFINITION
+
+
+      !!          WRITE COORDINATES
+      CALL sherr( NF90_PUT_VAR(id_f, id_lo, vx),  crtn,cf_in,cv_in)
+      CALL sherr( NF90_PUT_VAR(id_f, id_la, vy),  crtn,cf_in,cv_in)
+
+      !!          WRITE VARIABLE
+      CALL sherr( NF90_PUT_VAR(id_f, id_v, x2d),  crtn,cf_in,cv_in)
+
+      CALL sherr( NF90_CLOSE(id_f),  crtn,cf_in,cv_in)
+
+   END SUBROUTINE PHOVMOLLER
+
+
+
+
+
+
+
+
+
+
+
+   SUBROUTINE GET_SF_AO(cf_in, cv_in, rsf, rao)
+      !!
+      !!-----------------------------------------------------------------------
+      !! This routine extracts the 'scale_factor' and 'add_offset' of a given
+      !! variable from a netcdf file
+      !!
+      !! INPUT :
+      !! -------
+      !!          * cf_in      : name of the input file              (character)
+      !!          * cv_in      : name of the variable                (character)
+      !!
+      !! OUTPUT :
+      !! --------
+      !!          * rsf       : scale factor                        (real)
+      !!          * rao       : add offset                          (real)
+      !!
+      !!------------------------------------------------------------------------
+      !!
+      CHARACTER(len=*), INTENT(in) :: cf_in, cv_in
+      REAL(4),         INTENT(out) :: rsf, rao
+      !!
+      !! local :
+      INTEGER :: ierr1, ierr2
+      !!
+      crtn = 'GET_SF_AO'
+      !!
+      !!
+      CALL sherr( NF90_OPEN(cf_in, NF90_NOWRITE, id_f),  crtn,cf_in,cv_in)
+      !!
+      CALL sherr( NF90_INQ_VARID(id_f, cv_in, id_v),  crtn,cf_in,cv_in)
+      !!
+      ierr1 = NF90_GET_ATT(id_f, id_v, 'scale_factor', rsf)
+      ierr2 = NF90_GET_ATT(id_f, id_v, 'add_offset',   rao)
+      !!
+      IF ( (ierr1 /= NF90_NOERR).OR.(ierr2 /= NF90_NOERR) ) THEN
+         rsf = 1.      ;   rao = 0.
+         WRITE(6,*) 'WARNING: variable ', trim(cv_in), ' of file ',trim(cf_in), ' :'
+         WRITE(6,*) '       does not have a "scale_factor" and "add_offset" attributes'
+         WRITE(6,*) '       => scale_factor =', rsf; WRITE(6,*) '       => add_offset =', rao
+         PRINT *, ''
+      END IF
+      !!
+      CALL sherr( NF90_CLOSE(id_f),  crtn,cf_in,cv_in)
+      !!
+   END SUBROUTINE GET_SF_AO
+   !!
+   !!
+   !!
+   SUBROUTINE WHO_IS_MV(cf_in, cv_in, cmv_name, rmissval)
+      !!
+      !! Who is missing value???
+      !!
+      !!
+      CHARACTER(len=*),  INTENT(in)  :: cf_in, cv_in
+      CHARACTER(len=80), INTENT(out) :: cmv_name     !: real name of missing value
+      REAL(4),        INTENT(out) :: rmissval  !: value of the missing value
+      !!
+      LOGICAL    :: lmval
+      INTEGER    :: jmval
+      !!
+      !!
+      CALL CHECK_4_MISS(cf_in, cv_in, lmval, rmissval)
+      !!
+      cmv_name = 'missing_value'
+      !!
+      !! Maybe the name of missing value is different:
+      jmval = 0
+      DO WHILE ( .NOT. lmval )
+         !!
+         jmval = jmval + 1
+         cmv_name = trim(c_nm_missing_val(jmval))
+         WRITE(6,*) 'Trying "',trim(cmv_name),'"! instead of "missing_value..."'
+         CALL CHECK_4_MISS(cf_in, cv_in, lmval, rmissval, cmiss=cmv_name)
+         !!
+         IF ( ( jmval == nmval ) .AND. ( .NOT. lmval ) ) THEN
+            WRITE(6,*) 'Your input file does not contain a missing value!'
+            WRITE(6,*) 'Impossible to build a land sea mask array...'
+            WRITE(6,*) ' -> you should maybe specify the name of the "missing value"'
+            WRITE(6,*) '    found in the netcdf file into module "inter.f90"'
+            STOP
+         END IF
+         !!
+      END DO
+      !!
+      PRINT *, ''; WRITE(6,*) 'Missing value is called "',trim(cmv_name),'" !'
+      WRITE(6,*) 'and has the value', rmissval; PRINT *, ''
+      !!
+      !!
+      !!
+   END SUBROUTINE WHO_IS_MV
+   !!
+   !!
+   !!
+   SUBROUTINE sherr(ierr, croutine, ctf, ctv)
+      !!
+      !! To handle and display error messages
+      !!
+      INTEGER,            INTENT(in) :: ierr
+      !!
+      CHARACTER(len=*) , INTENT(in) :: &
+         &            ctf,           &    !: treated file
+         &            croutine,      &    !: routine name
+         &            ctv                 !: treated varible
+      !!
+      !!
+      IF ( ierr /= NF90_NOERR ) THEN
+         PRINT *, ''
+         WRITE(6,*) '************************************************'
+         WRITE(6,*) 'Error occured in procedure ', trim(croutine),' !'
+         PRINT *, ''
+         WRITE(6,*) 'Treated file     = ', trim(ctf)
+         WRITE(6,*) 'Treated variable = ', trim(ctv)
+         PRINT *, ''
+         WRITE(6,*) '--> aborting program'
+         PRINT *, ''
+         WRITE(6,*) 'Netcdf message was :'
+         WRITE(6,*) trim(NF90_STRERROR(ierr))
+         PRINT *, ''
+         WRITE(6,*) '************************************************'
+         PRINT *, ''
+         STOP
+      END IF
+      !!
+   END SUBROUTINE sherr
+
+
+
+
+
+   SUBROUTINE ctest_coor(rx, ry, rd, cdm)
+
+      !! Testing if 2D coordinates or 1D, and if match shape of data...
+
+      REAL(8), DIMENSION(:,:), INTENT(in)  :: rx, ry
+      REAL(4), DIMENSION(:,:), INTENT(in)  :: rd
+      CHARACTER(len=2)       , INTENT(out) :: cdm
+
+      INTEGER :: ix1, ix2, iy1, iy2, id1, id2
+
+      ix1 = size(rx,1) ; ix2 = size(rx,2)
+      iy1 = size(ry,1) ; iy2 = size(ry,2)
+      id1 = size(rd,1) ; id2 = size(rd,2)
+
+      IF ( (ix2 == 1).AND.(iy2 == 1) ) THEN
+
+         IF ( (ix1 == id1).AND.(iy1 == id2) ) THEN
+            cdm = '1d'
+         ELSE
+            CALL print_err('cdm', 'longitude and latitude array do not match data (1d)')
+         END IF
+
+      ELSE
+
+         IF ( (ix1 == id1).AND.(iy1 == id1).AND.(ix2 == id2).AND.(iy2 == id2) ) THEN
+            cdm = '2d'
+         ELSE
+            CALL print_err('cdm', 'longitude and latitude array do not match data (2d)')
+         END IF
+
+      END IF
+
+   END SUBROUTINE ctest_coor
+
+
+
+
+
+   SUBROUTINE prepare_nc(id_file, cdt0, nx, ny, cv_lon, cv_lat, cv_time, cu_t, vxtrm, &
+      &                id_ji, id_jj, id_jt, id_lon, id_lat, id_time, cri,cfi,cvi, cu_X, cu_Y)
+
+      INTEGER,                 INTENT(in)  :: id_file, nx, ny
+      CHARACTER(len=2),        INTENT(in)  :: cdt0
+      CHARACTER(len=*),        INTENT(in)  :: cv_lon, cv_lat, cv_time, cu_t, cri,cfi,cvi
+      REAL(8), DIMENSION(3,2), INTENT(in)  :: vxtrm
+      INTEGER,                 INTENT(out) :: id_ji, id_jj, id_jt, id_lon, id_lat, id_time
+
+      CHARACTER(len=*),        INTENT(in), OPTIONAL :: cu_X, cu_Y
+
+
+      CHARACTER(len=64) :: cu_X0, cu_Y0
+      INTEGER :: ierr
+
+      cu_X0 = 'degrees_east'
+      cu_Y0 = 'degrees_north'
+      IF ( present(cu_X) ) cu_X0 = trim(cu_X)
+      IF ( present(cu_Y) ) cu_Y0 = trim(cu_Y)
+
+
+
+
+      !!    HORIZONTAL
+      IF ( (trim(cv_lon) /= '').AND.(trim(cv_lat) /= '') ) THEN
+         !!
+         IF ( cdt0 == '2d' ) THEN
+            CALL sherr( NF90_DEF_DIM(id_file, 'x', nx, id_ji), cri,cfi,cvi)
+            CALL sherr( NF90_DEF_DIM(id_file, 'y', ny, id_jj), cri,cfi,cvi)
+            CALL sherr( NF90_DEF_VAR(id_file, trim(cv_lon), NF90_DOUBLE, (/id_ji,id_jj/), id_lon), cri,cfi,cvi)
+            CALL sherr( NF90_DEF_VAR(id_file, trim(cv_lat), NF90_DOUBLE, (/id_ji,id_jj/), id_lat), cri,cfi,cvi)
+            !!
+         ELSE IF ( cdt0 == '1d' ) THEN
+            CALL sherr( NF90_DEF_DIM(id_file, trim(cv_lon), nx, id_ji), cri,cfi,cvi)
+            CALL sherr( NF90_DEF_DIM(id_file, trim(cv_lat), ny, id_jj), cri,cfi,cvi)
+            CALL sherr( NF90_DEF_VAR(id_file, trim(cv_lon), NF90_DOUBLE, id_ji, id_lon), cri,cfi,cvi)
+            CALL sherr( NF90_DEF_VAR(id_file, trim(cv_lat), NF90_DOUBLE, id_jj, id_lat), cri,cfi,cvi)
+         END IF
+         !!
+         CALL sherr( NF90_PUT_ATT(id_file, id_lon,  'units', trim(cu_X0)), cri,cfi,cvi)
+         CALL sherr( NF90_PUT_ATT(id_file, id_lon, 'valid_min', vxtrm(1,1)), cri,cfi,cvi)
+         CALL sherr( NF90_PUT_ATT(id_file, id_lon, 'valid_max', vxtrm(1,2)), cri,cfi,cvi)
+         !!
+         CALL sherr( NF90_PUT_ATT(id_file, id_lat, 'units', trim(cu_Y0)), cri,cfi,cvi)
+         CALL sherr( NF90_PUT_ATT(id_file, id_lat, 'valid_min', vxtrm(2,1)), cri,cfi,cvi)
+         CALL sherr( NF90_PUT_ATT(id_file, id_lat, 'valid_max', vxtrm(2,2)), cri,cfi,cvi)
+         !!
+      ELSE
+         CALL sherr( NF90_DEF_DIM(id_file, 'x', nx, id_ji), cri,cfi,cvi)
+         CALL sherr( NF90_DEF_DIM(id_file, 'y', ny, id_jj), cri,cfi,cvi)
+      END IF
+      !!
+      !!  TIME
+      IF ( trim(cv_time) /= '' ) THEN
+         CALL sherr( NF90_DEF_DIM(id_file, trim(cv_time), NF90_UNLIMITED, id_jt), cri,cfi,cvi)
+         CALL sherr( NF90_DEF_VAR(id_file, trim(cv_time), NF90_DOUBLE, id_jt, id_time), cri,cfi,cvi)
+         CALL sherr( NF90_PUT_ATT(id_file, id_time, 'units',    trim(cu_t)), cri,cfi,cvi)
+         CALL sherr( NF90_PUT_ATT(id_file, id_time, 'valid_min',vxtrm(3,1)), cri,cfi,cvi)
+         CALL sherr( NF90_PUT_ATT(id_file, id_time, 'valid_max',vxtrm(3,2)), cri,cfi,cvi)
+      END IF
+      !!
+   END SUBROUTINE prepare_nc
+
+
+
+
+   SUBROUTINE print_err(crout, cmess)
+      CHARACTER(len=*), INTENT(in) :: crout, cmess
+      PRINT *, ''
+      WRITE(6,*) 'ERROR in ',trim(crout),' (io_ezcdf.f90): '
+      WRITE(6,*) trim(cmess) ; PRINT *, ''
+      STOP
+   END SUBROUTINE print_err
+
+
+
+
+END MODULE io_ezcdf

+ 294 - 0
compare_time-series.sh

@@ -0,0 +1,294 @@
+#!/usr/bin/env bash
+
+#==============================================================
+#
+#                    B A R A K U D A
+#
+#    An OCEAN MONITORING python environment for NEMO
+#
+#             L. Brodeau, 2009-2017
+#
+#===============================================================
+
+export script=compare_time-series
+[ -z ${BARAKUDA_ROOT+x} ] && export BARAKUDA_ROOT=${PWD}
+
+export FIG_FORMAT='png'
+#export FIG_FORMAT='svg'
+
+
+# Supported ORCA grids:
+ORCA_LIST="ORCA025.L75 ORCA1.L75 ORCA1.L46 ORCA1.L42 ORCA2 ORCA2_L46"
+
+# Display available configs:
+list_conf="`\ls ${BARAKUDA_ROOT}/configs/config_*.sh | sed -e "s|${BARAKUDA_ROOT}/configs\/config_||g" -e s/'.sh'/''/g`"
+# User configs, potentially in the directory from which barakuda.sh is called:
+list_conf+=" `\ls ./config_*.sh 2>/dev/null | sed -e "s|.\/config_||g" -e s/'.sh'/''/g`"
+
+
+# Important bash functions:
+. ${BARAKUDA_ROOT}/src/bash/bash_functions.bash
+
+usage()
+{
+    echo
+    echo "USAGE: ${0} -C <config> -R <exp1,exp2,...,expN>  (options)"
+    echo
+    echo "     Available configs are:"
+    for cc in ${list_conf}; do
+        echo "         * ${cc}"
+    done
+    echo
+    echo "   OPTIONS:"
+    echo "      -y <YYYY> => force initial year to YYYY"
+    echo
+    echo "      -O <cnfg1,cnfg2,...,cnfgN> => list of ORCA configs corresponding to"
+    echo "                                    <exp1,exp2,...,expN> in case they are"
+    echo "                                    not all on the same ORCA grid"
+    echo
+#    echo "      -c <exp>  => 2D comparison diagnostics are performed against exp <exp>"
+#    echo "                   instead of a climatology"
+#    echo
+    echo "      -f        => forces creation of diagnostic page eventhough treatment "
+    echo "                    of output files is not finished"
+    echo
+    echo "      -e        => create the HTML diagnostics page on local or remote server"
+    echo
+    echo "      -h        => print this message"
+    echo
+    exit
+}
+
+CEXPS="" ; # list of experiments separated by ","
+CORCS="" ; # corresponding list of ORCA configs in case CEXPS are not on the same ORCA grid!!!
+YEAR0="" ; iforcey0=0
+
+IPREPHTML=0
+IFORCENEW=0
+
+while getopts C:R:O:y:feh option ; do
+    case $option in
+        C) CONFIG=${OPTARG};;
+        R) CEXPS=${OPTARG};;
+        O) CORCS=${OPTARG};;
+        y) YEAR0=${OPTARG} ; iforcey0=1 ;;
+        f) IFORCENEW=1;;
+        e) IPREPHTML=1;;
+        h)  usage;;
+        \?) usage ;;
+    esac
+done
+
+
+
+
+
+if [ -z ${CONFIG} ] || [ -z ${CEXPS} ]; then usage ; exit ; fi
+
+
+
+for og in ${ORCA_LIST}; do
+    ca=""; ca=`echo ${CONFIG} | grep ${og}` ; if [ "${ca}" != "" ]; then ORCA=${og}; fi
+done
+if [ -z ${ORCA} ]; then echo "ORCA grid of config ${CONFIG} not supported yet"; exit; fi
+
+echo
+
+if [ -f ./config_${CONFIG}.sh ]; then
+    # sourcing local configuration file if present:
+    fconfig=./config_${CONFIG}.sh
+else
+    # sourcing barakuda-distribution configuration file:
+    fconfig=${BARAKUDA_ROOT}/configs/config_${CONFIG}.sh
+fi
+if [ -f ${fconfig} ]; then
+    echo "Sourcing configuration file: ${fconfig} !"
+    . ${fconfig}
+else
+    echo "PROBLEM: cannot find file ${fconfig} !"; exit
+fi
+echo
+
+
+LEXPS=`echo ${CEXPS} | sed -e s/'\,'/'\ '/g -e s/'\, '/'\ '/g`
+echo; echo "Experiments to be treated: ${LEXPS}"
+nbr=`echo ${LEXPS} | wc -w` ; echo "  => number of experiments to compare = ${nbr}"
+
+
+if [ "${CORCS}" = "" ]; then
+    if [ ! "${ORCA}" = "${CONF}" ]; then echo "ERROR: ORCA and CONF disagree! => ${ORCA} ${CONF}"; exit; fi
+    export ORCA=${CONF}
+else
+    LORCS=`echo ${CORCS} | sed -e s/'\,'/'\ '/g -e s/'\, '/'\ '/g`
+fi
+
+
+
+# Should be set from bash_fucntions:
+PYTH="${PYTHON_HOME}/bin/python -W ignore" ; # which Python installation to use
+export PYTHONPATH=${PYTHON_HOME}/lib/python2.7/site-packages:${BARAKUDA_ROOT}/python/modules ; # PATH to python barakuda modules
+PYBRKD_EXEC_PATH=${BARAKUDA_ROOT}/python/exec         ; # PATH to python barakuda executable
+#-------------------
+
+
+echo " NEMO grid = ${ORCA}";
+echo " reading config into: ${fconfig}"
+echo; echo
+
+#NEXPS="${ORCA}-`echo ${LEXPS} | sed -e 's/\ /_/g'`"
+NEXPS="`echo ${LEXPS} | sed -e 's/\ /_/g'`"
+echo " Label to be used: ${NEXPS}" ; echo
+
+BASE_NAME="comp_${NEXPS}"
+
+DIAG_COMP_DIR=${DIAG_DIR}/${BASE_NAME} ; rm -rf ${DIAG_COMP_DIR} ; mkdir -p ${DIAG_COMP_DIR}
+
+YEAR_INI=4000
+YEAR_END=0
+
+# just that they become arrays...
+VEXPS=( ${LEXPS} ) ;  VCONFEXPS=( ${LEXPS} ) ; VDIAGS=( ${LEXPS} ) ;
+
+if [ "${CORCS}" = "" ]; then
+    VORCS=( ${LEXPS} )
+else
+    VORCS=( ${LORCS} )
+fi
+
+jr=0
+
+for exp in ${LEXPS}; do
+
+    echo; echo " EXP ${exp} "
+    EXP="${exp}"
+
+    
+    echo "   => ORCA = ${ORCA}"
+    if [ "${CORCS}" = "" ]; then
+        VORCS[${jr}]=${ORCA}
+    fi
+
+
+    CONFEXP=${VORCS[${jr}]}-${EXP}
+    echo "   => CONFEXP = ${CONFEXP}"
+    VCONFEXPS[${jr}]=${CONFEXP}
+
+
+    DIAG_D="${DIAG_DIR}/${CONFEXP}"
+    VDIAGS[${jr}]=${DIAG_D}
+    echo "   => DIAG_D = ${DIAG_D} "; echo ; echo
+
+
+    if [ ! -d ${DIAG_D} ]; then
+        echo "PROBLEM: ${DIAG_D} does not exist!"
+        echo "    =>  you must run barakuda for ${exp} prior to comparison!"
+        exit
+    fi
+
+
+    # Guessing initial and last year:
+
+    check_if_file ${DIAG_D}/first_year.info
+    iy=`cat ${DIAG_D}/first_year.info`
+    if [ ${iy} -lt ${YEAR_INI} ]; then export YEAR_INI=${iy}; fi
+
+    check_if_file ${DIAG_D}/last_year_done.info
+    iy=`cat ${DIAG_D}/last_year_done.info`
+    if [ ${iy} -gt ${YEAR_END} ]; then export YEAR_END=${iy}; fi
+
+    ((jr++))
+done
+
+
+echo
+echo " Global YEAR_INI = ${YEAR_INI}"
+echo " Global YEAR_END = ${YEAR_END}"
+echo
+
+#echo " VEXPS => ${VEXPS[*]} "
+#echo " VORCS => ${VORCS[*]} "
+#echo " VCONFEXPS => ${VCONFEXPS[*]} "
+#echo " VDIAGS => ${VDIAGS[*]} "
+
+export LIST_EXPS=${LEXPS}
+export LIST_CONF=${VORCS[*]}
+
+echo
+echo "LIST_EXPS = ${LIST_EXPS}"
+echo "LIST_CONF = ${LIST_CONF}"
+echo
+
+
+
+cd ${DIAG_COMP_DIR}/
+
+${PYTH} ${PYBRKD_EXEC_PATH}/compare_time_series.py ${YEAR_INI} ${YEAR_END}
+
+
+# Starting to configure HTML index file:
+if [ "${EXTRA_CONF}" = "" ]; then echo "Problem, variable EXTRA_CONF is not set!" ; exit; fi
+TITLE="Ocean diagnostics<br>Comparison of experiments: \"${VEXPS[*]}\"<br>Configurations: \"${LIST_CONF}\""
+#if [ ${ece_exp} -gt 0 ]; then TITLE="${TITLE}<br>Atmospheric model: ${ATMO_INFO}"; fi
+
+export CONFEXP="Comparison"
+
+. ${BARAKUDA_ROOT}/src/bash/build_html.bash
+
+parse_html ${BARAKUDA_ROOT}/src/html/conf_start.html index.html
+
+
+list_figs=`\ls -v *.${FIG_FORMAT}`
+
+for ff in ${list_figs}; do
+    echo "<br><br><big> `echo ${ff} | sed -e s/.${FIG_FORMAT}//g -e s/_comparison//g` </big><br>" >> index.html
+    echo "  <img style=\"border: 0px solid\" alt=\"\" src=\"${ff}\"> <br>" >> index.html
+
+done
+
+cat ${BARAKUDA_ROOT}/src/html/conf_end.html >> index.html ; # Closing HTML file...
+
+cp ${BARAKUDA_ROOT}/src/html/conf_*.html  .
+if [ ${ece_exp} -eq 0 ]; then
+    cp ${BARAKUDA_ROOT}/src/html/logo.*g .
+else
+    cp ${BARAKUDA_ROOT}/src/html/logo_ece.svg ./logo.svg
+    cp ${BARAKUDA_ROOT}/src/html/logo_ece.png ./logo.png
+fi
+echo; echo
+
+
+if [ ${ihttp} -eq 0 ]; then
+
+    echo "Diagnostic page installed in `pwd`"
+    echo " => view this directory with a web browser (index.html)..."
+
+else
+
+    ssh ${RUSER}@${RHOST} "mkdir -p ${RWWWD}"
+
+    if [ ${ihttp} -eq 1 ]; then
+
+        echo "Preparing to export to remote host!"; echo
+
+        cd ../
+
+        tar cvf ${BASE_NAME}.tar ${BASE_NAME}
+        scp ${BASE_NAME}.tar ${RUSER}@${RHOST}:${RWWWD}/
+        ssh ${RUSER}@${RHOST} "cd ${RWWWD}/; rm -rf ${BASE_NAME}; tar xf ${BASE_NAME}.tar 2>/dev/null; rm -f ${BASE_NAME}.tar; chmod -R a+r ${BASE_NAME}"
+        rm -f ${BASE_NAME}.tar
+
+        echo; echo
+        echo "Diagnostic page installed on remote host ${RHOST} in ${RWWWD}/${BASE_NAME}!"
+        echo "( Also browsable on local host in `pwd`/${BASE_NAME} )"
+
+    else
+
+        echo "Error: \"ihttp\" is either 0 or 1 !"
+
+    fi
+
+fi
+
+rm -rf ${COMP_DIR}
+
+echo; echo

+ 234 - 0
configs/config_ORCA025_L75_T511_ece32_triolith.sh

@@ -0,0 +1,234 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for NEMO v3.6 of EC-Earth 3.2.2 on 75 levels
+#
+#        Machine: triolith.nsc.liu.se
+#
+#        L. Brodeau, 2017
+#
+#===========================================================
+
+export CONF=ORCA025.L75 ; # horizontal global ORCA configuration
+export NBL=75           ; # number of levels
+
+export HOST=TRIOLITH.nsc.liu.se ; # this has no importance at all, it will just become an "info" on the web-page!
+export MASTERMIND="SMHI / Uwe and Klaus" ; # same here, who's the person who designed/ran this simulation?
+
+export EXTRA_CONF="NEMO 3.6 + LIM 3 (EC-Earth 3.2.2)" ;   #  // same here ...
+
+# Path / directory structure in which to find NEMO output file (you can use
+# <ORCA> and <EXP> as substitute to your ORCA grid and experiment (EXP) name):
+export NEMO_OUT_STRCT="/proj/bolinc/users/x_laubr/run/<EXP>/output/nemo"
+
+# Path to root directory where to save the diagnostics (diagnostics for this "CONF"):
+export DIAG_DIR="/proj/bolinc/users/x_laubr/barakuda/ece32"
+
+# Path to directory containing some 2D and 3D climatologies on the relevant ORCA grid:
+export CONF_INI_DIR="/proj/bolinc/users/x_laubr/input_barakuda/ORCA025.L75_barakuda"
+
+# Temporary file system (scratch) on which to perform the job you can use <JOB_ID> if scracth depends on JOB ID:
+export SCRATCH="/scratch/local/<JOB_ID>"
+
+export PYTHON_HOME="/home/x_laubr/opt/Canopy_64bit/User" ; # HOME to python distribution with matplotlib and basemap !
+
+export DIR_NCVIEW_CMAP="${BARAKUDA_ROOT}/src/ncview_colormaps"
+
+# Is it an ec-earth experiment?
+export ece_exp=2 ; # 0 => not an EC-Earth experiment, it's a "pure" ocean-only NEMO experiment done from traditional NEMO setup
+#                  # 1 => it's an OCEAN-ONLY EC-Earth experiment done from a EC-Earth setup
+#                  # 2 => it's a  COUPLED  EC-Earth experiment
+#                  #      Both 1 and 2 imply that NEMO files are stored in something like
+#                  #       ${SOMEWHERE}/<EXP>/output/nemo/<YYY>
+#                  #       where YYY starts from '001' to
+#                  #      If you select '2', make sure 'cdo' is available and working!!!
+#                  # 10 => this experiment controled by AutoSubmit (so NEMO files are tared somerwhere?)
+#
+export Y_INI_EC=1990 ;    # initial year if ece_exp /= 0 !!!
+export M_INI_EC="01" ;    # initial month, only needed if ece_exp >= 10 !!!
+export NCHNKS_Y=1    ;    # number of chunks per year if ece_exp >= 10 (only needed if NCHNKS_Y >= 2 !)
+export TRES_IFS=511  ;    # spectral resolution for IFS, ex: T255 => TRES_IFS=255
+###--- end EC-Earth IFS relate section ---
+
+export ATMO_INFO="IFS T${TRES_IFS}" ; # Name of atmospheric model or forcing used (ex: COREv2, DFS5.2, IFS T255, ect...)
+
+# List of suffix of files that have been saved by NEMO and contain MONTHLY averages:
+export NEMO_SAVED_FILES="grid_T grid_U grid_V icemod SBC"
+
+export TSTAMP="1m"   ; # output time-frequency stamp as in NEMO output files...
+
+# In case 3D fields have been saved on an annual mean basis rather than montly:
+export ANNUAL_3D="" ;   # leave blanck "" if 3D fields are in monthly files...
+export NEMO_SAVED_FILES_3D="" ; #     ''
+
+# How does the nemo files prefix looks like
+# Everything before "<year_related_info>_grid_<X>" or "<year_related_info>_icemod"
+# use <ORCA>, <EXP> and <TSTAMP>=>  Ex: export NEMO_FILE_PREFIX="<ORCA>-<EXP>_<TSTAMP>_"
+export NEMO_FILE_PREFIX="<EXP>_<TSTAMP>_"
+# => should get rid of TSTAMP actually...
+
+
+####### NEMO => what fields in what files ??? ############
+#       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#   => depends on the XIOS *.xml setup you used...
+#   => always specify a string for the NN_* variables
+#      USE "X" if the field is not present in your NEMO output
+#
+# State variables and others in grid_T files:
+export NN_SST="tos"
+export NN_SSS="sos"
+export NN_SSH="zos"
+export NN_T="thetao"
+export NN_S="so"
+export NN_MLD="mldr10_1"
+#
+# State variables and others in grid_U files:
+export NN_U="uo"
+export NN_TAUX="tauuo"
+export NN_U_EIV="0" ; # 0 => ignore
+# State variables and others in grid_V files:
+export NN_V="vo"
+export NN_TAUY="tauvo"
+export NN_V_EIV="0" ; # 0 => ignore
+#
+# Sea-ice fields:
+export FILE_ICE_SUFFIX="icemod" ; # in what file type extension to find ice fields
+export NN_ICEF="siconc" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="sivolu" ; # ice thickness or rather volume...
+export NN_ICEU="sivelu" ; # ice U-velocity
+export NN_ICEV="sivelv" ; # ice V-velocity
+#
+# Surface fluxes:
+export FILE_FLX_SUFFIX="SBC" ; # in what file type extension to find surface fluxes (normally: "SBC")
+####                           # => mind that $FILE_FLX_SUFFIX must be also in NEMO_SAVED_FILES (above)
+#### Note: in fields marked with *+/-* you can use a sum or substraction of variables (no space allowed!)
+####       ex: NN_EMP="evap_ao_cea+subl_ai_cea-precip"
+####           NN_QNET="qsr+qnsol"
+# ++ Surface freswater fluxes:
+export NN_FWF="wfo"       ; # *+/-* name of net freshwater flux (E-P-R) in "FILE_FLX_SUFFIX" file...
+export NN_EMP="evap_ao_cea+subl_ai_cea-precip" ; # *+/-* name of E-P in "FILE_FLX_SUFFIX" file...
+export NN_P="precip"      ; # name of total precipitation (solid+liquid) in "FILE_FLX_SUFFIX" file...
+export NN_RNF="runoffs"   ; # name of continental runoffs in "FILE_FLX_SUFFIX" file...
+export NN_CLV="calving"   ; # calving from icebergs in "FILE_FLX_SUFFIX" file...
+export NN_E="evap_ao_cea+subl_ai_cea" ; # *+/-* name of total evaporation in "FILE_FLX_SUFFIX" file...
+# ++ Surface heat fluxes:
+export NN_QNET="qt_oce"   ; # *+/-* name of total net surface heat flux in "FILE_FLX_SUFFIX" file...
+export NN_QSOL="rsntds"   ; # name of net surface solar flux in "FILE_FLX_SUFFIX" file...
+# ++ Wind-stress module:
+export NN_TAUM="taum"        ; # name of surface wind stress module in "FILE_FLX_SUFFIX" file...
+export NN_WNDM="windsp"      ; # name of surface wind  speed module in "FILE_FLX_SUFFIX" file...
+#
+################################################################################################
+
+# Land-sea mask and basins files:
+export MM_FILE=${CONF_INI_DIR}/mesh_mask_ORCA025.L75_ece3.2_2017.nc4
+export BM_FILE=${BARAKUDA_ROOT}/data/basin_mask_ORCA025_ece3.2_2017.nc4
+
+# OBSERVATIONS / REFERENCES
+# 3D monthly climatologies of potential temperature and salinity (can be those you used for the NEMO experiment):
+export NM_TS_OBS="EN4.2.0 [1990-2010]"
+export F_T_OBS_3D_12=${CONF_INI_DIR}/thetao_EN.4.2.0_ORCA025L75_mclim_1990-2010.nc4
+export F_S_OBS_3D_12=${CONF_INI_DIR}/so_EN.4.2.0_ORCA025L75_mclim_1990-2010.nc4
+export F_SST_OBS_12=${CONF_INI_DIR}/thetao_EN.4.2.0_ORCA025L75_mclim_1990-2010.nc4
+export NN_T_OBS="thetao"
+export NN_S_OBS="so"
+export NN_SST_OBS="thetao"
+#
+# Sea-ice:
+export NM_IC_OBS="Hurrell et al 2008 [1980-1999]"
+export F_ICE_OBS_12=${CONF_INI_DIR}/ice_cover_180x360-ORCA025_Hurrell_monthly_mean1980-1999.nc4
+export NN_ICEF_OBS="ice_cover"
+#
+# Surface Heat fluxes:
+export NM_QSOL_OBS="NOCS 2.0 [1980-2005]"
+export F_QSOL_OBS_12=${BARAKUDA_ROOT}/data/obs/radsw_monthly_clim_1980-2005_NOCS2.nc4
+export NN_QSOL_OBS="radsw"
+
+
+# A text file where the cross sections (to compute transports) are defined :
+export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA025_y1050.dat"        ; # set i_do_trsp=1 !
+export TRANSPORT_SECTION_FILE_ICE="${BARAKUDA_ROOT}/data/transport_ice_ORCA025_y1050.dat"  ; # set i_do_trsp_ice=1 !
+
+# For transport by sigma-class:
+export DENSITY_SECTION_FILE="${BARAKUDA_ROOT}/data/dens_section_ORCA025_y1050.dat"
+
+# Files with the list of rectangular domains to "analyze" more closely:
+export FILE_DEF_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA025_y1050.txt"
+export FILE_DMV_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA025_y1050.txt"
+
+# In what format should figures be produced ('png' recommanded, but 'svg' supported!):
+export FIG_FORM="png"
+
+# About remote HOST to send/install HTML pages to:
+export ihttp=0                ; # do we export on a remote http server (1) or keep on the local machine (0)
+export RHOST=whitehouse.gov   ; # remote host to send diagnostic page to///
+export RUSER=donald           ; # username associated to remote host (for file export)
+export RWWWD=/data/www/barakuda/ec-earth_3.2b ; # directory of the local or remote host to send the diagnostic page to
+
+
+#########################
+# Diags to be performed #
+#########################
+
+# Movies of SST and SSS compared to OBS:
+export i_do_movi=1
+export iffmpeg_x264=0 ; # is, by chance, ffmpeg with support for x264 encoding available on your stystem? => 1 !
+
+# Basic 3D and surface averages:
+export i_do_mean=1
+
+# IFS surface fluxes of heat and freshwater
+export i_do_ifs_flx=0 ; # only relevant when ece_exp=2...
+
+# AMOC:
+export i_do_amoc=1
+export LMOCLAT="20-23 30-33 40-43 45-48 50-53" ; # List of latitude bands to look in for max of AMOC
+
+# Sea-ice diags
+export i_do_ice=1  ; # Sea-ice diags
+
+# Transport of mass, heat and salt through specified sections (into TRANSPORT_SECTION_FILE):
+export i_do_trsp=1  ; # transport of mass, heat and salt through specified sections
+#              # i_do_trsp=2 => treat also different depths range!
+z1_trsp=100  ; # first  depth: i_do_trsp must be set to 2
+z2_trsp=1000 ; # second depth: i_do_trsp must be set to 2
+
+# Solid freshwater transport through sections due to sea-ice drift
+export i_do_trsp_ice=1 ; # must have i_do_ice=1
+
+# Meridional heat/salt transport (advective)
+export i_do_mht=1
+
+# Transport by sigma class
+export i_do_sigt=1
+
+# Budget on pre-defined (FILE_DEF_BOXES) rectangular domains:
+export i_do_bb=0   ; # Budget and other stuffs on a given rectangular box!
+#             # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t)  (mean of 2D fields)
+
+# Vertical profiles on of box-averaged as a function of time...
+export i_do_box_TS_z=0 ; # do sigma vert. profiles on given boxes... # 1 => no figures, 2 => figures
+#                 # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t,z)
+
+# Deep Mixed volume in prescribed boxes:
+export i_do_dmv=0
+export MLD_CRIT="1000,725,500"
+
+# User-defined meridional or zonal cross sections (for temperature and salinity)
+# => TS_SECTION_FILE must be defined!
+export i_do_sect=1
+export TS_SECTION_FILE="${BARAKUDA_ROOT}/data/TS_sections.dat"
+
+
+# BETA / TESTING / NERDY (at your own risks...):
+#
+export i_do_ssx_box=0 ; # zoom on given boxes (+spatially-averaged values) for surface properties
+#                     # boxes defined into barakuda_orca.py ...
+
+# Some nerdy stuffs about the critical depth in prescribed boxes:
+export i_do_zcrit=0

+ 1 - 0
configs/config_ORCA025_L75_TEMPLATE.sh

@@ -0,0 +1 @@
+config_ORCA025_L75_T511_ece32_triolith.sh

+ 233 - 0
configs/config_ORCA025_L75_ece32_cca.sh

@@ -0,0 +1,233 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for NEMO v3.6 of EC-Earth 3.2.2 on 75 levels
+#
+#        Machine: cca/ccb ecmwf.int
+#
+#        L. Brodeau, 2017
+#        P. Le Sager, June 27, 2017
+#
+#===========================================================
+
+export CONF=ORCA025.L75 ; # horizontal global ORCA configuration
+export NBL=75           ; # number of levels
+
+export HOST="cca/ECMWF" ; # this has no importance at all, it will just become an "info" on the web-page!
+export MASTERMIND="KNMI / Philippe Le Sager" ; # same here, who's the person who designed/ran this simulation?
+
+export EXTRA_CONF="NEMO 3.6 + LIM 3 (EC-Earth 3.2.2)" ;   #  // same here ...
+
+# Path / directory structure in which to find NEMO output file (you can use
+# <ORCA> and <EXP> as substitute to your ORCA grid and experiment (EXP) name):
+export NEMO_OUT_STRCT="${ECE3_POSTPROC_RUNDIR}/<EXP>/output/nemo"
+
+# Path to root directory where to save the diagnostics (diagnostics for this "CONF"):
+export DIAG_DIR="$SCRATCH/barakuda/ece32"
+
+# Path to directory containing some 2D and 3D climatologies on the relevant ORCA grid:
+export CONF_INI_DIR="$SCRATCH/ECE-DATA/input_barakuda/ORCA025.L75_barakuda"
+
+# Temporary file system (scratch) on which to perform the job you can use <JOB_ID> if scracth depends on JOB ID:
+export SCRATCH="$SCRATCH"
+
+export PYTHON_HOME="/usr/local/apps/python/2.7.12-01/" ; # HOME to python distribution with matplotlib and basemap !
+
+export DIR_NCVIEW_CMAP="${BARAKUDA_ROOT}/src/ncview_colormaps"
+
+# Is it an ec-earth experiment?
+export ece_exp=2 ; # 0 => not an EC-Earth experiment, it's a "pure" ocean-only NEMO experiment done from traditional NEMO setup
+#                  # 1 => it's an OCEAN-ONLY EC-Earth experiment done from a EC-Earth setup
+#                  # 2 => it's a  COUPLED  EC-Earth experiment
+#                  #      Both 1 and 2 imply that NEMO files are stored in something like
+#                  #       ${SOMEWHERE}/<EXP>/output/nemo/<YYY>
+#                  #       where YYY starts from '001' to
+#                  #      If you select '2', make sure 'cdo' is available and working!!!
+#                  # 10 => this experiment controled by AutoSubmit (so NEMO files are tared somerwhere?)
+#
+export Y_INI_EC=1950 ;    # initial year if ece_exp /= 0 !!!
+export TRES_IFS=511  ;    # spectral resolution for IFS, ex: T255 => TRES_IFS=255
+###--- end EC-Earth IFS relate section ---
+
+export ATMO_INFO="IFS T${TRES_IFS}" ; # Name of atmospheric model or forcing used (ex: COREv2, DFS5.2, IFS T255, ect...)
+
+# List of suffix of files that have been saved by NEMO and contain MONTHLY averages:
+export NEMO_SAVED_FILES="grid_T grid_U grid_V icemod SBC"
+
+export TSTAMP="1m"   ; # output time-frequency stamp as in NEMO output files...
+
+# In case 3D fields have been saved on an annual mean basis rather than montly:
+export ANNUAL_3D="" ;   # leave blanck "" if 3D fields are in monthly files...
+export NEMO_SAVED_FILES_3D="" ; #     ''
+
+# How does the nemo files prefix looks like
+# Everything before "<year_related_info>_grid_<X>" or "<year_related_info>_icemod"
+# use <ORCA>, <EXP> and <TSTAMP>=>  Ex: export NEMO_FILE_PREFIX="<ORCA>-<EXP>_<TSTAMP>_"
+export NEMO_FILE_PREFIX="<EXP>_<TSTAMP>_"
+# => should get rid of TSTAMP actually...
+
+
+####### NEMO => what fields in what files ??? ############
+#       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#   => depends on the XIOS *.xml setup you used...
+#   => always specify a string for the NN_* variables
+#      USE "X" if the field is not present in your NEMO output
+#
+# State variables and others in grid_T files:
+export NN_SST="tos"
+export NN_SSS="sos"
+export NN_SSH="zos"
+export NN_T="thetao"
+export NN_S="so"
+export NN_MLD="mldr10_1"
+#
+# State variables and others in grid_U files:
+export NN_U="uo"
+export NN_TAUX="tauuo"
+export NN_U_EIV="0" ; # 0 => ignore
+# State variables and others in grid_V files:
+export NN_V="vo"
+export NN_TAUY="tauvo"
+export NN_V_EIV="0" ; # 0 => ignore
+#
+# Sea-ice fields:
+export FILE_ICE_SUFFIX="icemod" ; # in what file type extension to find ice fields
+export NN_ICEF="siconc" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="sivolu" ; # ice thickness or rather volume...
+export NN_ICEU="sivelu" ; # ice U-velocity
+export NN_ICEV="sivelv" ; # ice V-velocity
+#
+# Surface fluxes:
+export FILE_FLX_SUFFIX="SBC" ; # in what file type extension to find surface fluxes (normally: "SBC")
+####                           # => mind that $FILE_FLX_SUFFIX must be also in NEMO_SAVED_FILES (above)
+#### Note: in fields marked with *+/-* you can use a sum or substraction of variables (no space allowed!)
+####       ex: NN_EMP="evap_ao_cea+subl_ai_cea-precip"
+####           NN_QNET="qsr+qnsol"
+# ++ Surface freswater fluxes:
+export NN_FWF="wfo"       ; # *+/-* name of net freshwater flux (E-P-R) in "FILE_FLX_SUFFIX" file...
+export NN_EMP="evap_ao_cea+subl_ai_cea-precip" ; # *+/-* name of E-P in "FILE_FLX_SUFFIX" file...
+export NN_P="precip"      ; # name of total precipitation (solid+liquid) in "FILE_FLX_SUFFIX" file...
+export NN_RNF="runoffs"   ; # name of continental runoffs in "FILE_FLX_SUFFIX" file...
+export NN_CLV="calving"   ; # calving from icebergs in "FILE_FLX_SUFFIX" file...
+export NN_E="evap_ao_cea+subl_ai_cea" ; # *+/-* name of total evaporation in "FILE_FLX_SUFFIX" file...
+# ++ Surface heat fluxes:
+export NN_QNET="qt_oce"   ; # *+/-* name of total net surface heat flux in "FILE_FLX_SUFFIX" file...
+export NN_QSOL="rsntds"   ; # name of net surface solar flux in "FILE_FLX_SUFFIX" file...
+# ++ Wind-stress module:
+export NN_TAUM="taum"        ; # name of surface wind stress module in "FILE_FLX_SUFFIX" file...
+export NN_WNDM="windsp"      ; # name of surface wind  speed module in "FILE_FLX_SUFFIX" file...
+#
+################################################################################################
+
+# Land-sea mask and basins files:
+export MM_FILE=${CONF_INI_DIR}/mesh_mask_ORCA025.L75_ece3.2_2017.nc4
+export BM_FILE=${BARAKUDA_ROOT}/data/basin_mask_ORCA025_ece3.2_2017.nc4
+
+# OBSERVATIONS / REFERENCES
+# 3D monthly climatologies of potential temperature and salinity (can be those you used for the NEMO experiment):
+export NM_TS_OBS="EN4.2.0 [1990-2010]"
+export F_T_OBS_3D_12=${CONF_INI_DIR}/thetao_EN.4.2.0_ORCA025L75_mclim_1990-2010.nc4
+export F_S_OBS_3D_12=${CONF_INI_DIR}/so_EN.4.2.0_ORCA025L75_mclim_1990-2010.nc4
+export F_SST_OBS_12=${CONF_INI_DIR}/thetao_EN.4.2.0_ORCA025L75_mclim_1990-2010.nc4
+export NN_T_OBS="thetao"
+export NN_S_OBS="so"
+export NN_SST_OBS="thetao"
+#
+# Sea-ice:
+export NM_IC_OBS="Hurrell et al 2008 [1980-1999]"
+export F_ICE_OBS_12=${CONF_INI_DIR}/ice_cover_180x360-ORCA025_Hurrell_monthly_mean1980-1999.nc4
+export NN_ICEF_OBS="ice_cover"
+#
+# Surface Heat fluxes:
+export NM_QSOL_OBS="NOCS 2.0 [1980-2005]"
+export F_QSOL_OBS_12=${BARAKUDA_ROOT}/data/obs/radsw_monthly_clim_1980-2005_NOCS2.nc4
+export NN_QSOL_OBS="radsw"
+
+
+# A text file where the cross sections (to compute transports) are defined :
+export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA025_y1050.dat"        ; # set i_do_trsp=1 !
+export TRANSPORT_SECTION_FILE_ICE="${BARAKUDA_ROOT}/data/transport_ice_ORCA025_y1050.dat"  ; # set i_do_trsp_ice=1 !
+
+# For transport by sigma-class:
+export DENSITY_SECTION_FILE="${BARAKUDA_ROOT}/data/dens_section_ORCA025_y1050.dat"
+
+# Files with the list of rectangular domains to "analyze" more closely:
+export FILE_DEF_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA025_y1050.txt"
+export FILE_DMV_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA025_y1050.txt"
+
+# In what format should figures be produced ('png' recommanded, but 'svg' supported!):
+export FIG_FORM="png"
+
+# About remote HOST to send/install HTML pages to:
+export ihttp=0                ; # do we export on a remote http server (1) or keep on the local machine (0)
+export RHOST=whitehouse.gov   ; # remote host to send diagnostic page to///
+export RUSER=donald           ; # username associated to remote host (for file export)
+export RWWWD=/data/www/barakuda/ec-earth_3.2b ; # directory of the local or remote host to send the diagnostic page to
+
+
+#########################
+# Diags to be performed #
+#########################
+
+# Movies of SST and SSS compared to OBS:
+export i_do_movi=1
+export iffmpeg_x264=0 ; # is, by chance, ffmpeg with support for x264 encoding available on your stystem? => 1 !
+
+# Basic 3D and surface averages:
+export i_do_mean=1
+
+# IFS surface fluxes of heat and freshwater
+export i_do_ifs_flx=0 ; # only relevant when ece_exp=2...
+
+# AMOC:
+export i_do_amoc=1
+export LMOCLAT="20-23 30-33 40-43 45-48 50-53" ; # List of latitude bands to look in for max of AMOC
+
+# Sea-ice diags
+export i_do_ice=1  ; # Sea-ice diags
+
+# Transport of mass, heat and salt through specified sections (into TRANSPORT_SECTION_FILE):
+export i_do_trsp=1  ; # transport of mass, heat and salt through specified sections
+#              # i_do_trsp=2 => treat also different depths range!
+z1_trsp=100  ; # first  depth: i_do_trsp must be set to 2
+z2_trsp=1000 ; # second depth: i_do_trsp must be set to 2
+
+# Solid freshwater transport through sections due to sea-ice drift
+export i_do_trsp_ice=1 ; # must have i_do_ice=1
+
+# Meridional heat/salt transport (advective)
+export i_do_mht=1
+
+# Transport by sigma class
+export i_do_sigt=1
+
+# Budget on pre-defined (FILE_DEF_BOXES) rectangular domains:
+export i_do_bb=0   ; # Budget and other stuffs on a given rectangular box!
+#             # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t)  (mean of 2D fields)
+
+# Vertical profiles on of box-averaged as a function of time...
+export i_do_box_TS_z=0 ; # do sigma vert. profiles on given boxes... # 1 => no figures, 2 => figures
+#                 # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t,z)
+
+# Deep Mixed volume in prescribed boxes:
+export i_do_dmv=0
+export MLD_CRIT="1000,725,500"
+
+# User-defined meridional or zonal cross sections (for temperature and salinity)
+# => TS_SECTION_FILE must be defined!
+export i_do_sect=1
+export TS_SECTION_FILE="${BARAKUDA_ROOT}/data/TS_sections.dat"
+
+
+# BETA / TESTING / NERDY (at your own risks...):
+#
+export i_do_ssx_box=0 ; # zoom on given boxes (+spatially-averaged values) for surface properties
+#                     # boxes defined into barakuda_orca.py ...
+
+# Some nerdy stuffs about the critical depth in prescribed boxes:
+export i_do_zcrit=0

+ 227 - 0
configs/config_ORCA025_L75_etienne.sh

@@ -0,0 +1,227 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for NEMO v3.6 of EC-Earth 3.2 beta tunning on 75 levels
+#
+#        Machine: gustafson.bsc.es
+#
+#        L. Brodeau, 2017
+#
+#===========================================================
+
+export CONF=ORCA025.L75 ; # horizontal global ORCA configuration
+export NBL=75           ; # number of levels
+
+export HOST=`hostname`.bsc.es    ; # this has no importance at all, it will just become an "info" on the web-page!
+export MASTERMIND="BSC / Etienne" ; # same here, who's the person who designed/ran this simulation?
+
+export EXTRA_CONF="NEMO 3.6 + LIM 3 + IFS-T511 (EC-Earth 3.2b)<br>\
+<i>10 years spinup with constant CMIP5 forcing from 1940 using EC-Earth 3.2.0,<br>\
+and from 1950 onwards CMIP6 forcing using EC-Earth 3.2.1 (primavera branch)</i>" ;   #  // same here ...
+
+# Path / directory structure in which to find NEMO output file (you can use
+# <ORCA> and <EXP> as substitute to your ORCA grid and experiment (EXP) name):
+export NEMO_OUT_STRCT="/scratch/Earth/etourign/barakuda/<EXP>"
+
+# Path to root directory where to save the diagnostics (diagnostics for this "CONF"):
+export DIAG_DIR="/scratch/Earth/${USER}/barakuda/${CONF}_ece3"
+
+# Path to directory containing some 2D and 3D climatologies on the relevant ORCA grid:
+export CONF_INI_DIR="/esnas/obs/barakuda/ORCA025.L75_barakuda"
+
+# Temporary file system (scratch) on which to perform the job you can use <JOB_ID> if scracth depends on JOB ID:
+export SCRATCH="/scratch/Earth/${USER}"
+
+export PYTHON_HOME="/home/Earth/lbrodeau/opt/Canopy/User" ; # HOME to python distribution with matplotlib and basemap !
+
+export DIR_NCVIEW_CMAP="${BARAKUDA_ROOT}/src/ncview_colormaps"
+
+# Is it an ec-earth experiment?
+export ece_exp=0 ; # 0 => not an EC-Earth experiment, it's a "pure" ocean-only NEMO experiment done from traditional NEMO setup
+#                  # 1 => it's an OCEAN-ONLY EC-Earth experiment done from a EC-Earth setup
+#                  # 2 => it's a  COUPLED  EC-Earth experiment
+#                  #      Both 1 and 2 imply that NEMO files are stored in something like
+#                  #       ${SOMEWHERE}/<EXP>/output/nemo/<YYY>
+#                  #       where YYY starts from '001' to
+#                  #      If you select '2', make sure 'cdo' is available and working!!!
+#                  # 10 => this experiment controled by AutoSubmit (so NEMO files are tared somerwhere?)
+#
+export Y_INI_EC=1950 ;    # initial year if ece_exp /= 0 !!!
+export TRES_IFS=XXX  ;    # spectral resolution for IFS, ex: T255 => TRES_IFS=255
+###--- end EC-Earth IFS relate section ---
+
+export ATMO_INFO="IFS T511" ; # Name of atmospheric model or forcing used (ex: COREv2, DFS5.2, IFS T255, ect...)
+
+# List of suffix of files that have been saved by NEMO and contain MONTHLY averages:
+export NEMO_SAVED_FILES="grid_T"
+
+export TSTAMP="1m"   ; # output time-frequency stamp as in NEMO output files...
+
+# In case 3D fields have been saved on an annual mean basis rather than montly:
+export ANNUAL_3D="1y" ;   # leave blanck "" if 3D fields are in monthly files...
+export NEMO_SAVED_FILES_3D="grid_T grid_U grid_V" ; #     ''
+
+# How does the nemo files prefix looks like
+# Everything before "<year_related_info>_grid_<X>" or "<year_related_info>_icemod"
+# use <ORCA>, <EXP> and <TSTAMP>=>  Ex: export NEMO_FILE_PREFIX="<ORCA>-<EXP>_<TSTAMP>_"
+export NEMO_FILE_PREFIX="<EXP>_<TSTAMP>_"
+# => should get rid of TSTAMP actually...
+
+
+####### NEMO => what fields in what files ??? ############
+#       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#   => depends on the XIOS *.xml setup you used...
+#   => always specify a string for the NN_* variables
+#      USE "X" if the field is not present in your NEMO output
+#
+# State variables and others in grid_T files:
+export NN_SST="tos"
+export NN_SSS="sos"
+export NN_SSH="zos"
+export NN_T="thetao"
+export NN_S="so"
+export NN_MLD="mlotst"
+#
+# State variables and others in grid_U files:
+export NN_U="uo"
+export NN_TAUX="tauuo"
+export NN_U_EIV="0" ; # 0 => ignore
+# State variables and others in grid_V files:
+export NN_V="vo"
+export NN_TAUY="tauvo"
+export NN_V_EIV="0" ; # 0 => ignore
+#
+# Sea-ice fields:
+export FILE_ICE_SUFFIX="grid_T" ; # in what file type extension to find ice fields
+export NN_ICEF="siconc" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="sithic" ; # ice thickness or rather volume...
+export NN_ICEU="sivelu" ; # ice U-velocity
+export NN_ICEV="sivelv" ; # ice V-velocity
+#
+# Surface fluxes:
+export FILE_FLX_SUFFIX="grid_T" ; # in what file type extension to find surface fluxes
+####                           # => mind that $FILE_FLX_SUFFIX must be also in NEMO_SAVED_FILES (above)
+#### Note: in fields marked with *+/-* you can use a sum or substraction of variables (no space allowed!)
+####       ex: NN_EMP="evap_ao_cea+subl_ai_cea-precip"
+####           NN_QNET="qsr+qnsol"
+# ++ Surface freswater fluxes:
+export NN_FWF="X"        ; # name of net freshwater flux (E-P-R) in "FILE_FLX_SUFFIX" file...
+export NN_EMP="X"        ; # name of E-P in "FILE_FLX_SUFFIX" file...
+export NN_P="X"          ; # name of total precipitation (solid+liquid) in "FILE_FLX_SUFFIX" file...
+export NN_RNF="X"        ; # name of continental runoffs in "FILE_FLX_SUFFIX" file...
+export NN_CLV="X"        ; # calving from icebergs in "FILE_FLX_SUFFIX" file...
+export NN_E="X"          ; # name of total evaporation in "FILE_FLX_SUFFIX" file...
+# ++ Surface heat fluxes:
+export NN_QNET="hfds"    ; # name of total net surface heat flux in "FILE_FLX_SUFFIX" file...
+export NN_QSOL="rsntds"  ; # name of net surface solar flux in "FILE_FLX_SUFFIX" file...
+# ++ Wind-stress module:
+export NN_TAUM="X"         ; # name of Wind-stress module in "FILE_FLX_SUFFIX" file...
+export NN_WNDM="X"      ; # name of surface wind  speed module in "FILE_FLX_SUFFIX" file...
+#
+################################################################################################
+
+# Land-sea mask and basins files:
+export MM_FILE=${CONF_INI_DIR}/mesh_mask_ORCA025.L75_ece3.2_2017.nc4
+export BM_FILE=${BARAKUDA_ROOT}/data/basin_mask_ORCA025_ece3.2_2017.nc4
+
+# 3D monthly climatologies of potential temperature and salinity (can be those you used for the NEMO experiment):
+export NM_TS_OBS="EN4.2.0 [1990-2010]"
+export F_T_OBS_3D_12=${CONF_INI_DIR}/thetao_EN.4.2.0_ORCA025L75_mclim_1990-2010.nc4
+export F_S_OBS_3D_12=${CONF_INI_DIR}/so_EN.4.2.0_ORCA025L75_mclim_1990-2010.nc4
+export F_SST_OBS_12=${CONF_INI_DIR}/thetao_EN.4.2.0_ORCA025L75_mclim_1990-2010.nc4
+export NN_T_OBS="thetao"
+export NN_S_OBS="so"
+export NN_SST_OBS="thetao"
+#
+export NM_IC_OBS="Hurrell et al 2008 [1980-1999]"
+export F_ICE_OBS_12=${CONF_INI_DIR}/ice_cover_180x360-ORCA025_Hurrell_monthly_mean1980-1999.nc4
+export NN_ICEF_OBS="ice_cover"
+
+
+# A text file where the cross sections (to compute transports) are defined :
+export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA025_y1050.dat"        ; # set i_do_trsp=1 !
+export TRANSPORT_SECTION_FILE_ICE="${BARAKUDA_ROOT}/data/transport_ice_ORCA025_y1050.dat"  ; # set i_do_trsp_ice=1 !
+
+# For transport by sigma-class:
+export DENSITY_SECTION_FILE="${BARAKUDA_ROOT}/data/dens_section_ORCA025_y1050.dat"
+
+# Files with the list of rectangular domains to "analyze" more closely:
+export FILE_DEF_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA025_y1050.txt"
+export FILE_DMV_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA025_y1050.txt"
+
+# In what format should figures be produced ('png' recommanded, but 'svg' supported!):
+export FIG_FORM="png"
+
+# About remote HOST to send/install HTML pages to:
+export ihttp=1                  ; # do we export on a remote http server (1) or keep on the local machine (0)
+export RHOST=bscct01.bsc.es ; # remote host to send diagnostic page to///
+export RUSER=${USER}             ; # username associated to remote host (for file export)
+export RWWWD=/bsc/www/htdocs/public/${USER}/BaraKuda ; # directory of the local or remote host to send the diagnostic page to
+
+
+#########################
+# Diags to be performed #
+#########################
+
+# Movies of SST and SSS compared to OBS:
+export i_do_movi=1
+export iffmpeg_x264=1 ; # is, by chance, ffmpeg with support for x264 encoding available on your stystem?
+
+# Basic 3D and surface averages:
+export i_do_mean=1
+
+# IFS surface fluxes of heat and freshwater
+export i_do_ifs_flx=0 ; # only relevant when ece_exp=2...
+
+# AMOC:
+export i_do_amoc=1
+export LMOCLAT="20-23 30-33 40-43 45-48 50-53" ; # List of latitude bands to look in for max of AMOC
+
+# Sea-ice diags
+export i_do_ice=1  ; # Sea-ice diags
+
+# Transport of mass, heat and salt through specified sections (into TRANSPORT_SECTION_FILE):
+export i_do_trsp=1  ; # transport of mass, heat and salt through specified sections
+#              # i_do_trsp=2 => treat also different depths range!
+z1_trsp=100  ; # first  depth: i_do_trsp must be set to 2
+z2_trsp=1000 ; # second depth: i_do_trsp must be set to 2
+
+# Solid freshwater transport through sections due to sea-ice drift
+export i_do_trsp_ice=0 ; # must have i_do_ice=1
+
+# Meridional heat/salt transport (advective)
+export i_do_mht=1
+
+# Transport by sigma class
+export i_do_sigt=1
+
+# Budget on pre-defined (FILE_DEF_BOXES) rectangular domains:
+export i_do_bb=0   ; # Budget and other stuffs on a given rectangular box!
+#             # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t)  (mean of 2D fields)
+
+# Vertical profiles on of box-averaged as a function of time...
+export i_do_box_TS_z=0 ; # do sigma vert. profiles on given boxes... # 1 => no figures, 2 => figures
+#                 # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t,z)
+
+# Deep Mixed volume in prescribed boxes:
+export i_do_dmv=0
+export MLD_CRIT="1000,725,500"
+
+# User-defined meridional or zonal cross sections (for temperature and salinity)
+# => TS_SECTION_FILE must be defined!
+export i_do_sect=1
+export TS_SECTION_FILE="${BARAKUDA_ROOT}/data/TS_sections.dat"
+
+
+# BETA / TESTING / NERDY (at your own risks...):
+#
+export i_do_ssx_box=0 ; # zoom on given boxes (+spatially-averaged values) for surface properties
+#                     # boxes defined into barakuda_orca.py ...
+
+# Some nerdy stuffs about the critical depth in prescribed boxes:
+export i_do_zcrit=0

+ 233 - 0
configs/config_ORCA025_L75_rhino_knmi.sh

@@ -0,0 +1,233 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for NEMO v3.6 of EC-Earth 3.2.2 on 75 levels
+#
+#        Machine: cca/ccb ecmwf.int
+#
+#        L. Brodeau, 2017
+#        P. Le Sager, June 27, 2017
+#
+#===========================================================
+
+export CONF=ORCA025.L75 ; # horizontal global ORCA configuration
+export NBL=75           ; # number of levels
+
+export HOST="rhino" ; # this has no importance at all, it will just become an "info" on the web-page!
+export MASTERMIND="KNMI / Philippe Le Sager" ; # same here, who's the person who designed/ran this simulation?
+
+export EXTRA_CONF="NEMO 3.6 + LIM 3 (EC-Earth 3.2.2)" ;   #  // same here ...
+
+# Path / directory structure in which to find NEMO output file (you can use
+# <ORCA> and <EXP> as substitute to your ORCA grid and experiment (EXP) name):
+export NEMO_OUT_STRCT="${ECE3_POSTPROC_RUNDIR}/<EXP>/output/nemo"
+
+# Path to root directory where to save the diagnostics (diagnostics for this "CONF"):
+export DIAG_DIR="$SCRATCH/barakuda/ece322"
+
+# Path to directory containing some 2D and 3D climatologies on the relevant ORCA grid:
+export CONF_INI_DIR="${ECE3_POSTPROC_DATADIR}/post-proc/input_barakuda/ORCA025.L75_barakuda"
+
+# Temporary file system (scratch) on which to perform the job you can use <JOB_ID> if scracth depends on JOB ID:
+export SCRATCH="$SCRATCH"
+
+export PYTHON_HOME="/nfs/home/users/sager/anaconda2/" ; # HOME to python distribution with matplotlib and basemap !
+
+export DIR_NCVIEW_CMAP="${BARAKUDA_ROOT}/src/ncview_colormaps"
+
+# Is it an ec-earth experiment?
+export ece_exp=2 ; # 0 => not an EC-Earth experiment, it's a "pure" ocean-only NEMO experiment done from traditional NEMO setup
+#                  # 1 => it's an OCEAN-ONLY EC-Earth experiment done from a EC-Earth setup
+#                  # 2 => it's a  COUPLED  EC-Earth experiment
+#                  #      Both 1 and 2 imply that NEMO files are stored in something like
+#                  #       ${SOMEWHERE}/<EXP>/output/nemo/<YYY>
+#                  #       where YYY starts from '001' to
+#                  #      If you select '2', make sure 'cdo' is available and working!!!
+#                  # 10 => this experiment controled by AutoSubmit (so NEMO files are tared somerwhere?)
+#
+export Y_INI_EC=1950 ;    # initial year if ece_exp /= 0 !!!
+export TRES_IFS=511  ;    # spectral resolution for IFS, ex: T255 => TRES_IFS=255
+###--- end EC-Earth IFS related section ---
+
+export ATMO_INFO="IFS T${TRES_IFS}" ; # Name of atmospheric model or forcing used (ex: COREv2, DFS5.2, IFS T255, ect...)
+
+# List of suffix of files that have been saved by NEMO and contain MONTHLY averages:
+export NEMO_SAVED_FILES="grid_T grid_U grid_V icemod SBC"
+
+export TSTAMP="1m"   ; # output time-frequency stamp as in NEMO output files...
+
+# In case 3D fields have been saved on an annual mean basis rather than montly:
+export ANNUAL_3D="" ;   # leave blanck "" if 3D fields are in monthly files...
+export NEMO_SAVED_FILES_3D="" ; #     ''
+
+# How does the nemo files prefix looks like
+# Everything before "<year_related_info>_grid_<X>" or "<year_related_info>_icemod"
+# use <ORCA>, <EXP> and <TSTAMP>=>  Ex: export NEMO_FILE_PREFIX="<ORCA>-<EXP>_<TSTAMP>_"
+export NEMO_FILE_PREFIX="<EXP>_<TSTAMP>_"
+# => should get rid of TSTAMP actually...
+
+
+####### NEMO => what fields in what files ??? ############
+#       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#   => depends on the XIOS *.xml setup you used...
+#   => always specify a string for the NN_* variables
+#      USE "X" if the field is not present in your NEMO output
+#
+# State variables and others in grid_T files:
+export NN_SST="tos"
+export NN_SSS="sos"
+export NN_SSH="zos"
+export NN_T="thetao"
+export NN_S="so"
+export NN_MLD="mlotst"
+#
+# State variables and others in grid_U files:
+export NN_U="uo"
+export NN_TAUX="tauuo"
+export NN_U_EIV="0" ; # 0 => ignore
+# State variables and others in grid_V files:
+export NN_V="vo"
+export NN_TAUY="tauvo"
+export NN_V_EIV="0" ; # 0 => ignore
+#
+# Sea-ice fields:
+export FILE_ICE_SUFFIX="icemod" ; # in what file type extension to find ice fields
+export NN_ICEF="siconc" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="sivolu" ; # ice thickness or rather volume...
+export NN_ICEU="sivelu" ; # ice U-velocity
+export NN_ICEV="sivelv" ; # ice V-velocity
+#
+# Surface fluxes:
+export FILE_FLX_SUFFIX="SBC" ; # in what file type extension to find surface fluxes (normally: "SBC")
+####                           # => mind that $FILE_FLX_SUFFIX must be also in NEMO_SAVED_FILES (above)
+#### Note: in fields marked with *+/-* you can use a sum or substraction of variables (no space allowed!)
+####       ex: NN_EMP="evap_ao_cea+subl_ai_cea-precip"
+####           NN_QNET="qsr+qnsol"
+# ++ Surface freswater fluxes:
+export NN_FWF="wfo"       ; # *+/-* name of net freshwater flux (E-P-R) in "FILE_FLX_SUFFIX" file...
+export NN_EMP="evap_ao_cea+subl_ai_cea-precip" ; # *+/-* name of E-P in "FILE_FLX_SUFFIX" file...
+export NN_P="precip"      ; # name of total precipitation (solid+liquid) in "FILE_FLX_SUFFIX" file...
+export NN_RNF="runoffs"   ; # name of continental runoffs in "FILE_FLX_SUFFIX" file...
+export NN_CLV="calving"   ; # calving from icebergs in "FILE_FLX_SUFFIX" file...
+export NN_E="evap_ao_cea+subl_ai_cea" ; # *+/-* name of total evaporation in "FILE_FLX_SUFFIX" file...
+# ++ Surface heat fluxes:
+export NN_QNET="qt_oce"   ; # *+/-* name of total net surface heat flux in "FILE_FLX_SUFFIX" file...
+export NN_QSOL="rsntds"   ; # name of net surface solar flux in "FILE_FLX_SUFFIX" file...
+# ++ Wind-stress module:
+export NN_TAUM="taum"        ; # name of surface wind stress module in "FILE_FLX_SUFFIX" file...
+export NN_WNDM="windsp"      ; # name of surface wind  speed module in "FILE_FLX_SUFFIX" file...
+#
+################################################################################################
+
+# Land-sea mask and basins files:
+export MM_FILE=${CONF_INI_DIR}/mesh_mask_ORCA025.L75_ece3.2_2017.nc4
+export BM_FILE=${BARAKUDA_ROOT}/data/basin_mask_ORCA025_ece3.2_2017.nc4
+
+# OBSERVATIONS / REFERENCES
+# 3D monthly climatologies of potential temperature and salinity (can be those you used for the NEMO experiment):
+export NM_TS_OBS="EN4.2.0 [1990-2010]"
+export F_T_OBS_3D_12=${CONF_INI_DIR}/thetao_EN.4.2.0_ORCA025L75_mclim_1990-2010.nc4
+export F_S_OBS_3D_12=${CONF_INI_DIR}/so_EN.4.2.0_ORCA025L75_mclim_1990-2010.nc4
+export F_SST_OBS_12=${CONF_INI_DIR}/thetao_EN.4.2.0_ORCA025L75_mclim_1990-2010.nc4
+export NN_T_OBS="thetao"
+export NN_S_OBS="so"
+export NN_SST_OBS="thetao"
+#
+# Sea-ice:
+export NM_IC_OBS="Hurrell et al 2008 [1980-1999]"
+export F_ICE_OBS_12=${CONF_INI_DIR}/ice_cover_180x360-ORCA025_Hurrell_monthly_mean1980-1999.nc4
+export NN_ICEF_OBS="ice_cover"
+#
+# Surface Heat fluxes:
+export NM_QSOL_OBS="NOCS 2.0 [1980-2005]"
+export F_QSOL_OBS_12=${BARAKUDA_ROOT}/data/obs/radsw_monthly_clim_1980-2005_NOCS2.nc4
+export NN_QSOL_OBS="radsw"
+
+
+# A text file where the cross sections (to compute transports) are defined :
+export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA025_y1050.dat"        ; # set i_do_trsp=1 !
+export TRANSPORT_SECTION_FILE_ICE="${BARAKUDA_ROOT}/data/transport_ice_ORCA025_y1050.dat"  ; # set i_do_trsp_ice=1 !
+
+# For transport by sigma-class:
+export DENSITY_SECTION_FILE="${BARAKUDA_ROOT}/data/dens_section_ORCA025_y1050.dat"
+
+# Files with the list of rectangular domains to "analyze" more closely:
+export FILE_DEF_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA025_y1050.txt"
+export FILE_DMV_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA025_y1050.txt"
+
+# In what format should figures be produced ('png' recommanded, but 'svg' supported!):
+export FIG_FORM="png"
+
+# About remote HOST to send/install HTML pages to:
+export ihttp=0                ; # do we export on a remote http server (1) or keep on the local machine (0)
+export RHOST=whitehouse.gov   ; # remote host to send diagnostic page to///
+export RUSER=donald           ; # username associated to remote host (for file export)
+export RWWWD=/data/www/barakuda/ec-earth_3.2b ; # directory of the local or remote host to send the diagnostic page to
+
+
+#########################
+# Diags to be performed #
+#########################
+
+# Movies of SST and SSS compared to OBS:
+export i_do_movi=1
+export iffmpeg_x264=0 ; # is, by chance, ffmpeg with support for x264 encoding available on your stystem? => 1 !
+
+# Basic 3D and surface averages:
+export i_do_mean=1
+
+# IFS surface fluxes of heat and freshwater
+export i_do_ifs_flx=0 ; # only relevant when ece_exp=2...
+
+# AMOC:
+export i_do_amoc=1
+export LMOCLAT="20-23 30-33 40-43 45-48 50-53" ; # List of latitude bands to look in for max of AMOC
+
+# Sea-ice diags
+export i_do_ice=1  ; # Sea-ice diags
+
+# Transport of mass, heat and salt through specified sections (into TRANSPORT_SECTION_FILE):
+export i_do_trsp=1  ; # transport of mass, heat and salt through specified sections
+#              # i_do_trsp=2 => treat also different depths range!
+z1_trsp=100  ; # first  depth: i_do_trsp must be set to 2
+z2_trsp=1000 ; # second depth: i_do_trsp must be set to 2
+
+# Solid freshwater transport through sections due to sea-ice drift
+export i_do_trsp_ice=1 ; # must have i_do_ice=1
+
+# Meridional heat/salt transport (advective)
+export i_do_mht=1
+
+# Transport by sigma class
+export i_do_sigt=1
+
+# Budget on pre-defined (FILE_DEF_BOXES) rectangular domains:
+export i_do_bb=0   ; # Budget and other stuffs on a given rectangular box!
+#             # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t)  (mean of 2D fields)
+
+# Vertical profiles on of box-averaged as a function of time...
+export i_do_box_TS_z=0 ; # do sigma vert. profiles on given boxes... # 1 => no figures, 2 => figures
+#                 # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t,z)
+
+# Deep Mixed volume in prescribed boxes:
+export i_do_dmv=0
+export MLD_CRIT="1000,725,500"
+
+# User-defined meridional or zonal cross sections (for temperature and salinity)
+# => TS_SECTION_FILE must be defined!
+export i_do_sect=1
+export TS_SECTION_FILE="${BARAKUDA_ROOT}/data/TS_sections.dat"
+
+
+# BETA / TESTING / NERDY (at your own risks...):
+#
+export i_do_ssx_box=0 ; # zoom on given boxes (+spatially-averaged values) for surface properties
+#                     # boxes defined into barakuda_orca.py ...
+
+# Some nerdy stuffs about the critical depth in prescribed boxes:
+export i_do_zcrit=0

+ 202 - 0
configs/config_ORCA025_L75_v36_voima.sh

@@ -0,0 +1,202 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for NEMO v3.6 ORCA1 on 46 levels
+#
+#            HPC: voima.fmi.fi 
+#
+#        L. Brodeau, 2015
+#
+#===========================================================
+
+l_clim_diag=true ; # should we try to perform climatology-related diagnostics? (clim must be built!)
+
+export CONF=ORCA025.L75 ; # horizontal global configuration
+export NBL=75     ; # number of levels
+
+# Root directory where NEMO output files are stored:
+export STORE_DIR="/lustre/tmp/$USER"
+
+# List of suffixed of files that have been saved by NEMO:
+export NEMO_SAVED_FILES="grid_T grid_U grid_V icemod"
+
+
+# Directory structure in which to find NEMO output file (use <ORCA> and <RUN>):
+export NEMO_OUT_STRCT="${STORE_DIR}/<ORCA>/<ORCA>-<RUN>-S"
+
+export TSTAMP="1m"   ; # output time-frequency stamp as in NEMO output files...
+
+# How does the nemo files prefix looks like
+# Everything before "<year_related_info>_grid_<X>" or "<year_related_info>_icemod"
+# use <ORCA>, <RUN> and <TSTAMP>=>  Ex: export NEMO_FILE_PREFIX="<ORCA>-<RUN>_<TSTAMP>_"
+export NEMO_FILE_PREFIX="<ORCA>-<RUN>_<TSTAMP>_"
+# => should get rid of TSTAMP actually...
+
+# Temporary file system (scratch) on which to perform the job you can use <JOB_ID> if scracth depends on JOB ID:
+export SCRATCH="/lustre/tmp/$USER/tmp/<JOB_ID>"
+
+# Python installation directory where bin lib include reside
+export PYTHON_HOME=/opt/Python/2.7
+
+# NETCDF binaries such as nccopy
+export NCDF_BIN=/opt/cray/netcdf/4.3.0/bin
+
+# If variables names in NEMO files are not the default...
+export NN_SST="tos"
+export NN_SSS="sos"
+export NN_SSH="zos"
+export NN_T="thetao"
+export NN_S="so"
+export NN_MLD="mldr10_1"
+export NN_U="uo"
+export NN_V="vo"
+#export NN_U_EIV="vozoeivu"
+#export NN_V_EIV="vomeeivv"
+export NN_U_EIV="0" ; # ignore
+export NN_V_EIV="0" ; # ignore
+export NN_TAUX="tauuo"
+export NN_TAUY="tauvo"
+
+export NN_ICEF="siconc" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="sithic" ; # ice thickness but 'sit' is only in icemod file !!!
+
+
+export L_CONV2NC3=false ; # Set to true if your NEMO output is in Netcdf4 and your NCO does not support netcdf4!
+
+export L_RENAME=false ; # set to true if your ORCA output has old name convention (ex: votemper instead of thetao)
+
+
+export EXTRA_CONF="NEMO v3.6 ${CONF} (L${NBL}) - LIM3 / ocean-only experiment"
+
+# Land-sea mask and basins files:
+export MM_FILE="/lustre/tmp/uotilap/ecearth3/input/nemo/ORCA025L75/mesh_mask_ORCA025L75.nc"
+export BM_FILE="/lustre/tmp/uotilap/ecearth3/input/nemo/ORCA025L75/basin_mask_ORCA025L75.nc"
+
+# 3D monthly climatologies of potential temperature and salinity (can be those you used for the NEMO run):
+export CDATDIR=/stornext/field/users/${USER}
+export F_T_CLIM_3D_12=${CDATDIR}/tiede/PHC/PHC3.0.ORCA025.L75.nc
+export F_S_CLIM_3D_12=${CDATDIR}/tiede/PHC/PHC3.0.ORCA025.L75.nc
+export SST_CLIM_12=${CDATDIR}/tiede/PHC/PHC3.0.ORCA025.L75.nc
+export NN_T_CLIM="T"
+export NN_S_CLIM="S"
+export NN_SST_CLIM="sst"
+
+export ICE_CLIM_12=${CDATDIR}/sidads.colorado.edu/pub/DATASETS/NOAA/G02202_v2/seaice_conc_ymonmean_1994-2013.ORCA025.nc
+export NN_ICEF_CLIM="seaice_conc_monthly_cdr"
+
+
+# A text file where the vertical hydraugraphical sections of interest are defined :
+#export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_${CONF}_light.dat"
+export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA025.dat"
+
+# For transport by sigma-class:
+export DENSITY_SECTION_FILE="${BARAKUDA_ROOT}/data/dens_section_ORCA025.dat"
+
+
+# In what directory of the local machine to save the diagnostics:
+export DIAG_DIR="/lustre/tmp/${USER}/barakuda/${CONF}"
+
+
+# Files with the list of rectangular boxes to look at more closely:
+export FILE_DEF_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA025.txt"
+
+
+
+# About remote HOST to install HTML pages to:
+ihttp=0 ; # do we export on a remote http server (1) or keep on the local machine (0)
+RHOST=misu228.misu.su.se ; # remote host to send diagnostic page to///
+RUSER=laurent ; # username associated to remote host (for file export)
+RWWWD=/data/www/barakuda/${CONF} ; # directory of the local or remote host to send the diagnostic page to
+
+
+
+
+#########################
+# Diags to be performed #
+#########################
+
+
+
+
+
+# Basic 3D and surface averages:
+i_do_mean=1
+
+# AMOC:
+i_do_amoc=1
+export LMOCLAT="20-23 30-33 40-43 45-48 50-53" ; # List of latitude bands to look in for max of AMOC
+
+
+# Transport of mass, heat and salt through specified sections (into TRANSPORT_SECTION_FILE):
+i_do_trsp=2  ; # transport of mass, heat and salt through specified sections
+#              # i_do_trsp=2 => treat also different depths range!
+z1_trsp=100  ; # first  depth: i_do_trsp must be set to 2
+z2_trsp=1000 ; # second depth: i_do_trsp must be set to 2
+
+
+# meridional heat/salt transport (advective)
+i_do_mht=1
+
+# Transport by sigma class
+i_do_sigt=1
+
+# sea-ice diags
+i_do_ice=1  ; # Sea-ice diags
+export FILE_ICE_SUFFIX="icemod" ; # in what file to find ice fraction NN_ICEF? => "icemod" or "grid_T"
+
+
+i_do_bb=1   ; # Budget and other stuffs on a given rectangular box!
+#             # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t)  (mean of 2D fields)
+
+
+i_do_ssx_box=0 ; # zoom on given boxes (+spatially-averaged values) for surface properties
+#                # boxes defined into barakuda_orca.py ...
+
+
+# Vertical profiles on of box-averaged as a function of time...
+i_do_box_TS_z=1 ; # do sigma vert. profiles on given boxes... # 1 => no figures, 2 => figures
+#                 # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t,z)
+
+# 
+# Deep Mixed volume in prescribed boxes:
+i_do_dmv=1
+export MLD_CRIT="1000,725,500"
+
+
+
+
+# Some nerdy stuffs about the critical depth in prescribed boxes: 
+i_do_zcrit=0
+
+
+
+
+
+
+# BETA / TESTING:
+
+# Fresh-water transport associated to sea-ice transport
+#  => must compile cdficeflux.x but depends on more recent CDFTOOLS module...
+i_do_icet=0 ; # treat sea-ice volume transport!
+export TRANSPORT_ICE_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA025_ARCTIC.dat"
+
+
+
+
+i_do_flx=0  ; # surface fluxes diags
+
+
+
+
+i_do_amo=0 ;  # buit a SST time serie usable to build Atlantic Multidecadal Oscilation index
+
+
+i_do_sect=0 ; # do sigma vert. profiles on given boxes...
+VSECT_NM=( "Indian_77p5_E" "Atlantic_21p5_W" )
+VSECT_JI=(      "5,5"          "266,266"     ) ; # X range in C convention
+VSECT_JJ=(    "25,170"          "7,291"      ) ; # Y range in C convention

+ 225 - 0
configs/config_ORCA025_L75_valentina.sh

@@ -0,0 +1,225 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for NEMO v3.6 of EC-Earth 3.2 beta tunning on 75 levels
+#
+#        Machine: gustafson.bsc.es
+#
+#        L. Brodeau, 2017
+#
+#===========================================================
+
+export CONF=ORCA025.L75 ; # horizontal global ORCA configuration
+export NBL=75           ; # number of levels
+
+export HOST=`hostname`.bsc.es    ; # this has no importance at all, it will just become an "info" on the web-page!
+export MASTERMIND="BSC / Valentina" ; # same here, who's the person who designed/ran this simulation?
+
+export EXTRA_CONF="NEMO 3.6 + LIM 3 (EC-Earth 3.2b)" ;   #  // same here ...
+
+# Path / directory structure in which to find NEMO output file (you can use
+# <ORCA> and <EXP> as substitute to your ORCA grid and experiment (EXP) name):
+export NEMO_OUT_STRCT="/esnas/exp/ecearth/<EXP>/original_files/<Y_INI_EC>0101/fc0/outputs"
+
+# Path to root directory where to save the diagnostics (diagnostics for this "CONF"):
+export DIAG_DIR="/scratch/Earth/${USER}/barakuda/valentina"
+
+# Path to directory containing some 2D and 3D climatologies on the relevant ORCA grid:
+export CONF_INI_DIR="/esnas/obs/barakuda/ORCA025.L75_barakuda"
+
+# Temporary file system (scratch) on which to perform the job you can use <JOB_ID> if scracth depends on JOB ID:
+export SCRATCH="/scratch/Earth/${USER}"
+
+export PYTHON_HOME="/home/Earth/lbrodeau/opt/Canopy/User" ; # HOME to python distribution with matplotlib and basemap !
+
+export DIR_NCVIEW_CMAP="${BARAKUDA_ROOT}/src/ncview_colormaps"
+
+# Is it an ec-earth experiment?
+export ece_exp=10; # 0 => not an EC-Earth experiment, it's a "pure" ocean-only NEMO experiment done from traditional NEMO setup
+#                  # 1 => it's an OCEAN-ONLY EC-Earth experiment done from a EC-Earth setup
+#                  # 2 => it's a  COUPLED  EC-Earth experiment
+#                  #      Both 1 and 2 imply that NEMO files are stored in something like
+#                  #       ${SOMEWHERE}/<EXP>/output/nemo/<YYY>
+#                  #       where YYY starts from '001' to
+#                  #      If you select '2', make sure 'cdo' is available and working!!!
+#                  # 10 => this experiment controled by AutoSubmit (so NEMO files are tared somerwhere?)
+#
+export Y_INI_EC=1960 ;    # initial year if ece_exp /= 0 !!!
+export NCHNKS_Y=2    ;    # number of chunks per year (only needed if NCHNKS_Y >= 2 !)
+export TRES_IFS=XXX  ;    # spectral resolution for IFS, ex: T255 => TRES_IFS=255
+###--- end EC-Earth IFS relate section ---
+
+export ATMO_INFO="IFS T${TRES_IFS}" ; # Name of atmospheric model or forcing used (ex: COREv2, DFS5.2, IFS T255, ect...)
+
+# List of suffix of files that have been saved by NEMO and contain MONTHLY averages:
+export NEMO_SAVED_FILES="grid_T grid_U grid_V icemod"
+
+export TSTAMP="1m"   ; # output time-frequency stamp as in NEMO output files...
+
+# In case 3D fields have been saved on an annual mean basis rather than montly:
+export ANNUAL_3D="" ;   # leave blanck "" if 3D fields are in monthly files...
+export NEMO_SAVED_FILES_3D="" ; #     ''
+
+# How does the nemo files prefix looks like
+# Everything before "<year_related_info>_grid_<X>" or "<year_related_info>_icemod"
+# use <ORCA>, <EXP> and <TSTAMP>=>  Ex: export NEMO_FILE_PREFIX="<ORCA>-<EXP>_<TSTAMP>_"
+export NEMO_FILE_PREFIX="<EXP>_<TSTAMP>_"
+# => should get rid of TSTAMP actually...
+
+
+####### NEMO => what fields in what files ??? ############
+#       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#   => depends on the XIOS *.xml setup you used...
+#   => always specify a string for the NN_* variables
+#      USE "X" if the field is not present in your NEMO output
+#
+# State variables and others in grid_T files:
+export NN_SST="sosstsst"
+export NN_SSS="vosaline"
+export NN_SSH="sossheig"
+export NN_T="votemper"
+export NN_S="vosaline"
+export NN_MLD="mldr10_1"
+#
+# State variables and others in grid_U files:
+export NN_U="vozocrtx"
+export NN_TAUX="sozotaux"
+export NN_U_EIV="0" ; # 0 => ignore
+# State variables and others in grid_V files:
+export NN_V="vomecrty"
+export NN_TAUY="sometauy"
+export NN_V_EIV="0" ; # 0 => ignore
+#
+# Sea-ice fields:
+export FILE_ICE_SUFFIX="icemod" ; # in what file type extension to find ice fields
+export NN_ICEF="siconc" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="sivolu" ; # ice thickness or rather volume...
+export NN_ICEU="sivelu" ; # ice U-velocity
+export NN_ICEV="sivelv" ; # ice V-velocity
+#
+# Surface fluxes:
+export FILE_FLX_SUFFIX="grid_T" ; # in what file type extension to find surface fluxes
+####                           # => mind that $FILE_FLX_SUFFIX must be also in NEMO_SAVED_FILES (above)
+#### Note: in fields marked with *+/-* you can use a sum or substraction of variables (no space allowed!)
+####       ex: NN_EMP="evap_ao_cea+subl_ai_cea-precip"
+####           NN_QNET="qsr+qnsol"
+# ++ Surface freswater fluxes:
+export NN_FWF="X"        ; # name of net freshwater flux (E-P-R) in "FILE_FLX_SUFFIX" file...
+export NN_EMP="X"        ; # name of E-P in "FILE_FLX_SUFFIX" file...
+export NN_P="X"          ; # name of total precipitation (solid+liquid) in "FILE_FLX_SUFFIX" file...
+export NN_RNF="X"   ; # name of continental runoffs in "FILE_FLX_SUFFIX" file...
+export NN_CLV="X"        ; # calving from icebergs in "FILE_FLX_SUFFIX" file...
+export NN_E="X"          ; # name of total evaporation in "FILE_FLX_SUFFIX" file...
+# ++ Surface heat fluxes:
+export NN_QNET="qt_oce"       ; # name of total net surface heat flux in "FILE_FLX_SUFFIX" file...
+export NN_QSOL="qsr_oce"  ; # name of net surface solar flux in "FILE_FLX_SUFFIX" file...
+# ++ Wind-stress module:
+export NN_TAUM="X"        ; # name of surface wind stress module in "FILE_FLX_SUFFIX" file...
+export NN_WNDM="X"      ; # name of surface wind  speed module in "FILE_FLX_SUFFIX" file...
+#
+################################################################################################
+
+# Land-sea mask and basins files:
+export MM_FILE=${CONF_INI_DIR}/mesh_mask_ORCA025.L75_ece3.2_2017.nc4
+export BM_FILE=${BARAKUDA_ROOT}/data/basin_mask_ORCA025_ece3.2_2017.nc4
+
+# 3D monthly climatologies of potential temperature and salinity (can be those you used for the NEMO experiment):
+export NM_TS_OBS="EN4.2.0 [1990-2010]"
+export F_T_OBS_3D_12=${CONF_INI_DIR}/thetao_EN.4.2.0_ORCA025L75_mclim_1990-2010.nc4
+export F_S_OBS_3D_12=${CONF_INI_DIR}/so_EN.4.2.0_ORCA025L75_mclim_1990-2010.nc4
+export F_SST_OBS_12=${CONF_INI_DIR}/thetao_EN.4.2.0_ORCA025L75_mclim_1990-2010.nc4
+export NN_T_OBS="thetao"
+export NN_S_OBS="so"
+export NN_SST_OBS="thetao"
+#
+export NM_IC_OBS="Hurrell et al 2008 [1980-1999]"
+export F_ICE_OBS_12=${CONF_INI_DIR}/ice_cover_180x360-ORCA025_Hurrell_monthly_mean1980-1999.nc4
+export NN_ICEF_OBS="ice_cover"
+
+
+# A text file where the cross sections (to compute transports) are defined :
+export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA025_y1050.dat"
+
+# For transport by sigma-class:
+export DENSITY_SECTION_FILE="${BARAKUDA_ROOT}/data/dens_section_ORCA025_y1050.dat"
+
+# Files with the list of rectangular domains to "analyze" more closely:
+export FILE_DEF_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA025_y1050.txt"
+export FILE_DMV_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA025_y1050.txt"
+
+# In what format should figures be produced ('png' recommanded, but 'svg' supported!):
+export FIG_FORM="png"
+
+# About remote HOST to send/install HTML pages to:
+export ihttp=1                  ; # do we export on a remote http server (1) or keep on the local machine (0)
+export RHOST=bscct01.bsc.es ; # remote host to send diagnostic page to///
+export RUSER=${USER}             ; # username associated to remote host (for file export)
+export RWWWD=/bsc/www/htdocs/public/${USER}/BaraKuda ; # directory of the local or remote host to send the diagnostic page to
+
+
+#########################
+# Diags to be performed #
+#########################
+
+# Movies of SST and SSS compared to OBS:
+export i_do_movi=1
+export iffmpeg_x264=0 ; # is, by chance, ffmpeg with support for x264 encoding available on your stystem?
+
+# Basic 3D and surface averages:
+export i_do_mean=1
+
+# IFS surface fluxes of heat and freshwater
+export i_do_ifs_flx=0 ; # only relevant when ece_exp=2...
+
+# AMOC:
+export i_do_amoc=1
+export LMOCLAT="20-23 30-33 40-43 45-48 50-53" ; # List of latitude bands to look in for max of AMOC
+
+# Sea-ice diags
+export i_do_ice=1  ; # Sea-ice diags
+
+# Transport of mass, heat and salt through specified sections (into TRANSPORT_SECTION_FILE):
+export i_do_trsp=1  ; # transport of mass, heat and salt through specified sections
+#              # i_do_trsp=2 => treat also different depths range!
+z1_trsp=100  ; # first  depth: i_do_trsp must be set to 2
+z2_trsp=1000 ; # second depth: i_do_trsp must be set to 2
+
+# Solid freshwater transport through sections due to sea-ice drift
+export i_do_trsp_ice=1 ; # must have i_do_ice=1
+
+# Meridional heat/salt transport (advective)
+export i_do_mht=1
+
+# Transport by sigma class
+export i_do_sigt=1
+
+# Budget on pre-defined (FILE_DEF_BOXES) rectangular domains:
+export i_do_bb=0   ; # Budget and other stuffs on a given rectangular box!
+#             # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t)  (mean of 2D fields)
+
+# Vertical profiles on of box-averaged as a function of time...
+export i_do_box_TS_z=0 ; # do sigma vert. profiles on given boxes... # 1 => no figures, 2 => figures
+#                 # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t,z)
+
+# Deep Mixed volume in prescribed boxes:
+export i_do_dmv=0
+export MLD_CRIT="1000,725,500"
+
+# User-defined meridional or zonal cross sections (for temperature and salinity)
+# => TS_SECTION_FILE must be defined!
+export i_do_sect=1
+export TS_SECTION_FILE="${BARAKUDA_ROOT}/data/TS_sections.dat"
+
+
+# BETA / TESTING / NERDY (at your own risks...):
+#
+export i_do_ssx_box=0 ; # zoom on given boxes (+spatially-averaged values) for surface properties
+#                     # boxes defined into barakuda_orca.py ...
+
+# Some nerdy stuffs about the critical depth in prescribed boxes:
+export i_do_zcrit=0

+ 223 - 0
configs/config_ORCA1_L42_ece22_triolith.sh

@@ -0,0 +1,223 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for NEMO v2.? and EC-Earth 2.2 / 2.3 (CMIP5)
+#
+#        Machine: triolith.nsc.liu.se
+#
+#        L. Brodeau, 2017
+#
+#===========================================================
+
+export CONF=ORCA1.L42 ; # horizontal global ORCA configuration
+export NBL=42         ; # number of levels
+
+export HOST=TRIOLITH.nsc.liu.se ; # this has no importance at all, it will just become an "info" on the web-page!
+export MASTERMIND="MISU / Laurent" ; # same here, who's the person who designed/ran this simulation?
+
+export EXTRA_CONF="LIM2, NEMO 2.X (EC-Earth 2_CMIP5)" ;   #  // same here ...
+
+# Path / directory structure in which to find NEMO output file (you can use
+# <ORCA> and <EXP> as substitute to your ORCA grid and experiment (EXP) name):
+export NEMO_OUT_STRCT="/proj/bolinc/users/x_laubr/CMIP5/<EXP>-SAVED/NEMO"
+
+# Path to root directory where to save the diagnostics (diagnostics for this "CONF"):
+export DIAG_DIR="/proj/bolinc/users/x_laubr/barakuda/cmip5"
+
+# Path to directory containing some 2D and 3D climatologies on the relevant ORCA grid:
+export CONF_INI_DIR="/proj/bolinc/users/x_laubr/${CONF}/${CONF}-I"
+
+# Temporary file system (scratch) on which to perform the job you can use <JOB_ID> if scracth depends on JOB ID:
+export SCRATCH="/scratch/local/<JOB_ID>"
+
+export PYTHON_HOME="/home/x_laubr/opt/Canopy_64bit/User" ; # HOME to python distribution with matplotlib and basemap !
+
+export DIR_NCVIEW_CMAP="${BARAKUDA_ROOT}/src/ncview_colormaps"
+
+# Is it an ec-earth experiment?
+export ece_exp=0 ; # 0 => not an EC-Earth experiment, it's a "pure" ocean-only NEMO experiment done from traditional NEMO setup
+#                  # 1 => it's an OCEAN-ONLY EC-Earth experiment done from a EC-Earth setup
+#                  # 2 => it's a  COUPLED  EC-Earth experiment
+#                  #      Both 1 and 2 imply that NEMO files are stored in something like
+#                  #       ${SOMEWHERE}/<EXP>/output/nemo/<YYY>
+#                  #       where YYY starts from '001' to
+#                  #      If you select '2', make sure 'cdo' is available and working!!!
+#                  # 10 => this experiment controled by AutoSubmit (so NEMO files are tared somerwhere?)
+#
+export Y_INI_EC=1990 ;    # initial year if ec-earth experiment...
+export TRES_IFS=XXX  ;    # spectral resolution for IFS, ex: T255 => TRES_IFS=255
+###--- end EC-Earth IFS relate section ---
+
+export ATMO_INFO="IFS T159" ; # Name of atmospheric model or forcing used (ex: COREv2, DFS5.2, IFS T255, ect...)
+
+# List of suffix of files that have been saved by NEMO and contain MONTHLY averages:
+export NEMO_SAVED_FILES="grid_T grid_U grid_V icemod"
+
+export TSTAMP="MM"   ; # output time-frequency stamp as in NEMO output files...
+
+# In case 3D fields have been saved on an annual mean basis rather than montly:
+export ANNUAL_3D="" ;   # leave blanck "" if 3D fields are in monthly files...
+export NEMO_SAVED_FILES_3D="" ; #     ''
+
+# How does the nemo files prefix looks like
+# Everything before "<year_related_info>_grid_<X>" or "<year_related_info>_icemod"
+# use <ORCA>, <EXP> and <TSTAMP>=>  Ex: export NEMO_FILE_PREFIX="<ORCA>-<EXP>_<TSTAMP>_"
+export NEMO_FILE_PREFIX="ORCA1-<EXP>_<TSTAMP>_"
+# => should get rid of TSTAMP actually...
+
+
+####### NEMO => what fields in what files ??? ############
+#       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#   => depends on the XIOS *.xml setup you used...
+#   => always specify a string for the NN_* variables
+#      USE "X" if the field is not present in your NEMO output
+#
+# State variables and others in grid_T files:
+export NN_SST="sosstsst"
+export NN_SSS="sosaline"
+export NN_SSH="sossheig"
+export NN_T="votemper"
+export NN_S="vosaline"
+export NN_MLD="somxl010"
+#
+# State variables and others in grid_U files:
+export NN_U="vozocrtx"
+export NN_TAUX="sozotaux"
+export NN_U_EIV="0" ; # 0 => ignore
+# State variables and others in grid_V files:
+export NN_V="vomecrty"
+export NN_TAUY="sometauy"
+export NN_V_EIV="0" ; # 0 => ignore
+#
+# Sea-ice fields:
+export FILE_ICE_SUFFIX="icemod" ; # in what file type extension to find ice fields
+export NN_ICEF="ileadfra" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="iicethic" ; # ice thickness but 'sit' is only in icemod file !!!
+export NN_ICEU="X" ; # ice U-velocity
+export NN_ICEV="X" ; # ice V-velocity
+#
+# Surface fluxes:
+export FILE_FLX_SUFFIX="grid_T" ; # in what file type extension to find surface fluxes
+####                           # => mind that $FILE_FLX_SUFFIX must be also in NEMO_SAVED_FILES (above)
+#### Note: in fields marked with *+/-* you can use a sum or substraction of variables (no space allowed!)
+####       ex: NN_EMP="evap_ao_cea+subl_ai_cea-precip"
+####           NN_QNET="qsr+qnsol"
+# ++ Surface freswater fluxes:
+export NN_FWF="sowaflup"       ; # *+/-* name of net freshwater flux (E-P-R) in "FILE_FLX_SUFFIX" file...
+export NN_EMP="X"              ; # *+/-* name of E-P in "FILE_FLX_SUFFIX" file...
+export NN_P="X"                ; # name of total precipitation (solid+liquid) in "FILE_FLX_SUFFIX" file...
+export NN_RNF="sorunoff"       ; # name of continental runoffs in "FILE_FLX_SUFFIX" file...
+export NN_CLV="X"              ; # calving from icebergs in "FILE_FLX_SUFFIX" file...
+export NN_E="X"                ; # *+/-* name of total evaporation in "FILE_FLX_SUFFIX" file...
+# ++ Surface heat fluxes:
+export NN_QNET="sohefldo"      ; # *+/-* name of total net surface heat flux in "FILE_FLX_SUFFIX" file...
+export NN_QSOL="soshfldo"      ; # name of net surface solar flux in "FILE_FLX_SUFFIX" file...
+# ++ Wind-stress module:
+export NN_TAUM="X"             ; # name of Wind-stress module in "FILE_FLX_SUFFIX" file...
+export NN_WNDM="X"      ; # name of surface wind  speed module in "FILE_FLX_SUFFIX" file...
+#
+################################################################################################
+
+# Land-sea mask and basins files:
+export MM_FILE="${CONF_INI_DIR}/mesh_mask_ORCA1_ecearth2_42l_NoCaspian.nc4"
+export BM_FILE="${BARAKUDA_ROOT}/data/basin_mask_ORCA1_ece2.2_cmip5.nc4"
+
+# 3D monthly climatologies of potential temperature and salinity (can be those you used for the NEMO experiment):
+export F_T_OBS_3D_12="${CONF_INI_DIR}/thetao_1degx1deg-ORCA1.L75_WOA2009_monthly.nc4"
+export F_S_OBS_3D_12="${CONF_INI_DIR}/so_1degx1deg-ORCA1.L75_WOA2009_monthly.nc4"
+export F_SST_OBS_12="/proj/bolinc/users/x_laubr/ORCA1.L75/ORCA1.L75-I/tos_180x360-ORCA1_Reynolds_monthly_mean1982-2005.nc"
+export NN_T_OBS="thetao"
+export NN_S_OBS="so"
+export NN_SST_OBS="tos"
+
+export F_ICE_OBS_12="/proj/bolinc/users/x_laubr/ORCA1.L75/ORCA1.L75-I/ice_cover_180x360-ORCA1_Hurrell_monthly_mean1980-1999.nc4"
+export NN_ICEF_OBS="ice_cover"
+
+
+# A text file where the cross sections (to compute transports) are defined :
+export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA1.dat"        ; # set i_do_trsp=1 !
+export TRANSPORT_SECTION_FILE_ICE="${BARAKUDA_ROOT}/data/transport_ice_ORCA1.dat"  ; # set i_do_trsp_ice=1 !
+
+# For transport by sigma-class:
+export DENSITY_SECTION_FILE="${BARAKUDA_ROOT}/data/dens_section_ORCA1.dat"
+
+# Files with the list of rectangular domains to "analyze" more closely:
+export FILE_DEF_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA1_ece2.txt"
+export FILE_DMV_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA1_ece2.txt"
+
+# In what format should figures be produced ('png' recommanded, but 'svg' supported!):
+export FIG_FORM="png"
+
+# About remote HOST to install HTML pages to:
+export ihttp=0 ; # do we export on a remote http server (1) or keep on the local machine (0)
+export RHOST=misu228.misu.su.se ; # remote host to send diagnostic page to///
+export RUSER=laurent ; # username associated to remote host (for file export)
+export RWWWD=/data/www/barakuda/CMIP5 ; # directory of the local or remote host to send the diagnostic page to
+
+
+#########################
+# Diags to be performed #
+#########################
+
+# Movies of SST and SSS compared to OBS:
+export i_do_movi=1
+export iffmpeg_x264=0 ; # is, by chance, ffmpeg with support for x264 encoding available on your stystem? => 1 !
+
+# Basic 3D and surface averages:
+export i_do_mean=1
+
+# IFS surface fluxes of heat and freshwater
+export i_do_ifs_flx=0 ; # only relevant when ece_exp=2...
+
+# AMOC:
+export i_do_amoc=1
+export LMOCLAT="20-23 30-33 40-43 45-48 50-53" ; # List of latitude bands to look in for max of AMOC
+
+# Sea-ice diags
+export i_do_ice=1  ; # Sea-ice diags
+
+# Transport of mass, heat and salt through specified sections (into TRANSPORT_SECTION_FILE):
+export i_do_trsp=1  ; # transport of mass, heat and salt through specified sections
+#              # i_do_trsp=2 => treat also different depths range!
+z1_trsp=100  ; # first  depth: i_do_trsp must be set to 2
+z2_trsp=1000 ; # second depth: i_do_trsp must be set to 2
+
+# Solid freshwater transport through sections due to sea-ice drift
+export i_do_trsp_ice=0 ; # must have i_do_ice=1
+
+# Meridional heat/salt transport (advective)
+export i_do_mht=1
+
+# Transport by sigma class
+export i_do_sigt=1
+
+# Budget on pre-defined (FILE_DEF_BOXES) rectangular domains:
+export i_do_bb=1   ; # Budget and other stuffs on a given rectangular box!
+#             # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t)  (mean of 2D fields)
+
+# Vertical profiles on of box-averaged as a function of time...
+export i_do_box_TS_z=1 ; # do sigma vert. profiles on given boxes... # 1 => no figures, 2 => figures
+#                 # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t,z)
+
+# Deep Mixed volume in prescribed boxes:
+export i_do_dmv=1
+export MLD_CRIT="1000,725,500,100,0"
+
+# User-defined meridional or zonal cross sections (for temperature and salinity)
+# => TS_SECTION_FILE must be defined!
+export i_do_sect=1
+export TS_SECTION_FILE="${BARAKUDA_ROOT}/data/TS_sections.dat"
+
+
+# BETA / TESTING / NERDY (at your own risks...):
+#
+export i_do_ssx_box=0 ; # zoom on given boxes (+spatially-averaged values) for surface properties
+#                     # boxes defined into barakuda_orca.py ...
+
+# Some nerdy stuffs about the critical depth in prescribed boxes:
+export i_do_zcrit=0

+ 222 - 0
configs/config_ORCA1_L46_ece31_valentina.sh

@@ -0,0 +1,222 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for EC-Earth 3.1 on ORCA1 with 46 levels
+#
+#        Machine: gustafson@BSC
+#
+#        L. Brodeau, 2017
+#
+#===========================================================
+
+export CONF=ORCA1.L46 ; # horizontal global ORCA configuration
+export NBL=46         ; # number of levels
+
+export HOST=GUSTAFSON ; # this has no importance at all, it will just become an "info" on the web-page!
+export MASTERMIND="BSC / Valentina" ; # same here, who's the person who designed/ran this simulation?
+
+export EXTRA_CONF="EC-Earth 3.1" ;   #  // same here ...
+
+# Path / directory structure in which to find NEMO output file (you can use
+# <ORCA> and <EXP> as substitute to your ORCA grid and experiment (EXP) name):
+#export NEMO_OUT_STRCT="/esnas/exp/ecearth/<EXP>/original_files/<Y_INI_EC>0101/fc0/outputs"
+export NEMO_OUT_STRCT="/esnas/exp/ecearth/<EXP>/original_files/<Y_INI_EC>0201/fc0/outputs"
+
+# Path to root directory where to save the diagnostics (diagnostics for this "CONF"):
+export DIAG_DIR="/scratch/Earth/${USER}/barakuda/valentina"
+
+# Path to directory containing some 2D and 3D climatologies on the relevant ORCA grid:
+export CONF_INI_DIR="/esnas/obs/barakuda/ORCA1.L46"
+
+# Temporary file system (scratch) on which to perform the job you can use <JOB_ID> if scracth depends on JOB ID:
+export SCRATCH="/scratch/Earth/${USER}"
+
+export PYTHON_HOME="/home/Earth/lbrodeau/opt/Canopy/User" ; # HOME to python distribution with matplotlib and basemap !
+
+export DIR_NCVIEW_CMAP="${BARAKUDA_ROOT}/src/ncview_colormaps"
+
+# Is it an ec-earth (or autosubmit-controlled) experiment?
+export ece_exp=10; # 0 => not an EC-Earth experiment, it's a "pure" ocean-only NEMO experiment done from traditional NEMO setup
+#                  # 1 => it's an OCEAN-ONLY EC-Earth experiment done from a EC-Earth setup
+#                  # 2 => it's a  COUPLED  EC-Earth experiment
+#                  #      Both 1 and 2 imply that NEMO files are stored in something like
+#                  #       ${SOMEWHERE}/<EXP>/output/nemo/<YYY>
+#                  #       where YYY starts from '001' to
+#                  #      If you select '2', make sure 'cdo' is available and working!!!
+#                  # 10 => this experiment controled by AutoSubmit (so NEMO files are tared somerwhere...)
+#
+export Y_INI_EC=1950 ;    # initial year,  only needed if ece_exp /= 0  !!!
+export M_INI_EC=02   ;    # initial month, only needed if ece_exp >= 10 !!!
+export NCHNKS_Y=4    ;    # number of chunks per year if ece_exp >= 10 (only needed if NCHNKS_Y >= 2 !)
+export TRES_IFS=XXX  ;    # spectral resolution for IFS (only needed if ece_exp=2), ex: T255 => TRES_IFS=255
+###--- end EC-Earth IFS relate section ---
+
+export ATMO_INFO="???" ; # Name of atmospheric model or forcing used (ex: COREv2, DFS5.2, IFS T255, ect...)
+
+# List of suffix of files that have been saved by NEMO and contain MONTHLY averages:
+export NEMO_SAVED_FILES="grid_T grid_U grid_V icemod"
+
+export TSTAMP="1m"   ; # output time-frequency stamp as in NEMO output files...
+
+# In case 3D fields have been saved on an annual mean basis rather than montly:
+export ANNUAL_3D="" ;   # leave blanck "" if 3D fields are in monthly files...
+export NEMO_SAVED_FILES_3D="" ; #     ''
+
+# How does the nemo files prefix looks like
+# Everything before "<year_related_info>_grid_<X>" or "<year_related_info>_icemod"
+# use <ORCA>, <EXP> and <TSTAMP>=>  Ex: export NEMO_FILE_PREFIX="<ORCA>-<EXP>_<TSTAMP>_"
+export NEMO_FILE_PREFIX="<EXP>_<TSTAMP>_"
+# => should get rid of TSTAMP actually...
+
+
+####### NEMO => what fields in what files ??? ############
+#       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#   => depends on the XIOS *.xml setup you used...
+#   => always specify a string for the NN_* variables
+#      USE "X" if the field is not present in your NEMO output
+#
+# State variables and others in grid_T files:
+export NN_SST="sosstsst"
+export NN_SSS="vosaline"
+export NN_SSH="sossheig"
+export NN_T="votemper"
+export NN_S="vosaline"
+export NN_MLD="somxl010"
+#
+# State variables and others in grid_U files:
+export NN_U="vozocrtx"
+export NN_TAUX="sozotaux"
+export NN_U_EIV="0" ; # 0 => ignore
+# State variables and others in grid_V files:
+export NN_V="vomecrty"
+export NN_TAUY="sometauy"
+export NN_V_EIV="0" ; # 0 => ignore
+#
+# Sea-ice fields:
+export FILE_ICE_SUFFIX="icemod" ; # in what file type extension to find ice fields
+export NN_ICEF="iiceconc" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="iicethic" ; # ice thickness or rather volume...
+#
+# Surface fluxes:
+export FILE_FLX_SUFFIX="grid_T" ; # in what file type extension to find surface fluxes
+# ++ Surface freswater fluxes:
+export NN_FWF="X"        ; # name of net freshwater flux (E-P-R) in "FILE_FLX_SUFFIX" file...
+export NN_EMP="X"        ; # name of E-P in "FILE_FLX_SUFFIX" file...
+export NN_P="X"          ; # name of total precipitation (solid+liquid) in "FILE_FLX_SUFFIX" file...
+export NN_RNF="X"   ; # name of continental runoffs in "FILE_FLX_SUFFIX" file...
+export NN_CLV="X"        ; # calving from icebergs in "FILE_FLX_SUFFIX" file...
+export NN_E="X"          ; # name of total evaporation in "FILE_FLX_SUFFIX" file...
+# ++ Surface heat fluxes:
+export NN_QNET="sohefldo"  ; # name of total net surface heat flux in "FILE_FLX_SUFFIX" file...
+export NN_QSOL="soshfldo"  ; # name of net surface solar flux in "FILE_FLX_SUFFIX" file...
+# ++ Wind-stress module:
+export NN_TAUM="X"        ; # name of surface wind stress module in "FILE_FLX_SUFFIX" file...
+export NN_WNDM="X"      ; # name of surface wind  speed module in "FILE_FLX_SUFFIX" file...
+#
+################################################################################################
+
+# Land-sea mask and basins files:
+export MM_FILE=${CONF_INI_DIR}/mesh_mask_ORCA1L46_ece31.nc4
+export BM_FILE=${BARAKUDA_ROOT}/data/basin_mask_ORCA1_ece2.2_cmip5.nc4 ; # 3.1 has same horizontal mask with 2.2
+
+# 3D monthly climatologies of potential temperature and salinity (can be those you used for the NEMO experiment):
+export F_T_OBS_3D_12=${CONF_INI_DIR}/thetao_1degx1deg-ORCA1_L46_WOA2009_monthly.nc4
+export F_S_OBS_3D_12=${CONF_INI_DIR}/so_1degx1deg-ORCA1_L46_WOA2009_monthly.nc4
+export F_SST_OBS_12=${CONF_INI_DIR}/tos_180x360-ORCA1_Reynolds_monthly_mean1982-2005.nc4
+export NN_T_OBS="thetao"
+export NN_S_OBS="so"
+export NN_SST_OBS="tos"
+
+export F_ICE_OBS_12=${CONF_INI_DIR}/ice_cover_180x360-ORCA1_Hurrell_monthly_mean1980-1999.nc4
+export NN_ICEF_OBS="ice_cover"
+
+
+# A text file where the cross sections (to compute transports) are defined :
+export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA1.dat"
+
+# For transport by sigma-class:
+export DENSITY_SECTION_FILE="${BARAKUDA_ROOT}/data/dens_section_ORCA1.dat"
+
+# Files with the list of rectangular domains to "analyze" more closely:
+export FILE_DEF_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA1.txt"
+export FILE_DMV_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA1.txt"
+
+# In what format should figures be produced ('png' recommanded, but 'svg' supported!):
+export FIG_FORM="png"
+
+# About remote HOST to send/install HTML pages to:
+export ihttp=1                  ; # do we export on a remote http server (1) or keep on the local machine (0)
+export RHOST=bscct01.bsc.es ; # remote host to send diagnostic page to///
+export RUSER=${USER}             ; # username associated to remote host (for file export)
+export RWWWD=/bsc/www/htdocs/public/${USER}/BaraKuda ; # directory of the local or remote host to send the diagnostic page to
+
+
+#########################
+# Diags to be performed #
+#########################
+
+# Movies of SST and SSS compared to OBS:
+export i_do_movi=1
+export iffmpeg_x264=1 ; # is, by chance, ffmpeg with support for x264 encoding available on your stystem?
+
+# Basic 3D and surface averages:
+export i_do_mean=1
+
+# IFS surface fluxes of heat and freshwater
+export i_do_ifs_flx=0 ; # only relevant when ece_exp=2...
+
+# AMOC:
+export i_do_amoc=1
+export LMOCLAT="20-23 30-33 40-43 45-48 50-53" ; # List of latitude bands to look in for max of AMOC
+
+# Transport of mass, heat and salt through specified sections (into TRANSPORT_SECTION_FILE):
+export i_do_trsp=1  ; # transport of mass, heat and salt through specified sections
+#              # i_do_trsp=2 => treat also different depths range!
+z1_trsp=100  ; # first  depth: i_do_trsp must be set to 2
+z2_trsp=1000 ; # second depth: i_do_trsp must be set to 2
+
+# Meridional heat/salt transport (advective)
+export i_do_mht=1
+
+# Transport by sigma class
+export i_do_sigt=1
+
+# Sea-ice diags
+export i_do_ice=1  ; # Sea-ice diags
+
+# Budget on pre-defined (FILE_DEF_BOXES) rectangular domains:
+export i_do_bb=0   ; # Budget and other stuffs on a given rectangular box!
+#             # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t)  (mean of 2D fields)
+
+# Vertical profiles on of box-averaged as a function of time...
+export i_do_box_TS_z=0 ; # do sigma vert. profiles on given boxes... # 1 => no figures, 2 => figures
+#                 # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t,z)
+
+# Deep Mixed volume in prescribed boxes:
+export i_do_dmv=0
+export MLD_CRIT="1000,725,500"
+
+# User-defined meridional or zonal cross sections (for temperature and salinity)
+# => TS_SECTION_FILE must be defined!
+export i_do_sect=1
+export TS_SECTION_FILE="${BARAKUDA_ROOT}/data/TS_sections.dat"
+
+
+# BETA / TESTING / NERDY (at your own risks...):
+#
+export i_do_ssx_box=0 ; # zoom on given boxes (+spatially-averaged values) for surface properties
+#                     # boxes defined into barakuda_orca.py ...
+
+# Some nerdy stuffs about the critical depth in prescribed boxes:
+export i_do_zcrit=0
+
+# Fresh-water transport associated to sea-ice transport
+#  => must compile cdficeflux.x but depends on more recent CDFTOOLS module...
+export i_do_icet=0 ; # treat sea-ice volume transport!
+export TRANSPORT_ICE_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA1_ARCTIC.dat"
+

+ 21 - 0
configs/config_ORCA1_L46_v36_LIM2_voima.sh

@@ -0,0 +1,21 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for NEMO v3.6 ORCA1 on 46 levels and LIM2
+#
+#            HPC: voima.fmi.fi 
+#
+#        L. Brodeau, 2015
+#
+#===========================================================
+
+. ./configs/config_ORCA1_L46_v36_voima.sh
+
+# LIM2 exceptions
+export NN_ICEF="ice_pres" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="sit" ; # ice thickness but 'sit' is only in icemod file !!!
+export EXTRA_CONF="NEMO v3.6 ${CONF} (L${NBL}) - LIM2 / ocean-only experiment"
+

+ 202 - 0
configs/config_ORCA1_L46_v36_voima.sh

@@ -0,0 +1,202 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for NEMO v3.6 ORCA1 on 46 levels
+#
+#            HPC: voima.fmi.fi 
+#
+#        L. Brodeau, 2015
+#
+#===========================================================
+
+l_clim_diag=true ; # should we try to perform climatology-related diagnostics? (clim must be built!)
+
+export CONF=ORCA1.L46 ; # horizontal global configuration
+export NBL=46     ; # number of levels
+
+# Root directory where NEMO output files are stored:
+export STORE_DIR="/lustre/tmp/$USER"
+
+# List of suffixed of files that have been saved by NEMO:
+export NEMO_SAVED_FILES="grid_T grid_U grid_V icemod"
+
+
+# Directory structure in which to find NEMO output file (use <ORCA> and <RUN>):
+export NEMO_OUT_STRCT="${STORE_DIR}/<ORCA>/<ORCA>-<RUN>-S"
+
+export TSTAMP="1m"   ; # output time-frequency stamp as in NEMO output files...
+
+# How does the nemo files prefix looks like
+# Everything before "<year_related_info>_grid_<X>" or "<year_related_info>_icemod"
+# use <ORCA>, <RUN> and <TSTAMP>=>  Ex: export NEMO_FILE_PREFIX="<ORCA>-<RUN>_<TSTAMP>_"
+export NEMO_FILE_PREFIX="<ORCA>-<RUN>_<TSTAMP>_"
+# => should get rid of TSTAMP actually...
+
+# Temporary file system (scratch) on which to perform the job you can use <JOB_ID> if scracth depends on JOB ID:
+export SCRATCH="/lustre/tmp/$USER/tmp/<JOB_ID>"
+
+# Python installation directory where bin lib include reside
+export PYTHON_HOME=/opt/Python/2.7
+
+# NETCDF binaries such as nccopy
+export NCDF_BIN=/opt/cray/netcdf/4.3.0/bin
+
+# If variables names in NEMO files are not the default...
+export NN_SST="tos"
+export NN_SSS="sos"
+export NN_SSH="zos"
+export NN_T="thetao"
+export NN_S="so"
+export NN_MLD="mldr10_1"
+export NN_U="uo"
+export NN_V="vo"
+#export NN_U_EIV="vozoeivu"
+#export NN_V_EIV="vomeeivv"
+export NN_U_EIV="0" ; # ignore
+export NN_V_EIV="0" ; # ignore
+export NN_TAUX="tauuo"
+export NN_TAUY="tauvo"
+
+export NN_ICEF="siconc" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="sithic" ; # ice thickness but 'sit' is only in icemod file !!!
+
+
+export L_CONV2NC3=false ; # Set to true if your NEMO output is in Netcdf4 and your NCO does not support netcdf4!
+
+export L_RENAME=false ; # set to true if your ORCA output has old name convention (ex: votemper instead of thetao)
+
+
+export EXTRA_CONF="NEMO v3.6 ${CONF} (L${NBL}) - LIM3 / ocean-only experiment"
+
+# Land-sea mask and basins files:
+export MM_FILE="/lustre/tmp/uotilap/ecearth3/input/nemo/ORCA1L46/mesh_mask_ORCA1L46.nc"
+export BM_FILE="/lustre/tmp/uotilap/ecearth3/input/nemo/ORCA1L46/basin_mask_ORCA1L46.nc"
+
+# 3D monthly climatologies of potential temperature and salinity (can be those you used for the NEMO run):
+export CDATDIR=/stornext/field/users/${USER}
+export F_T_CLIM_3D_12=${CDATDIR}/tiede/PHC/PHC3.0.ORCA1.L46.nc
+export F_S_CLIM_3D_12=${CDATDIR}/tiede/PHC/PHC3.0.ORCA1.L46.nc
+export SST_CLIM_12=${CDATDIR}/tiede/PHC/PHC3.0.ORCA1.L46.nc
+export NN_T_CLIM="T"
+export NN_S_CLIM="S"
+export NN_SST_CLIM="sst"
+
+export ICE_CLIM_12=${CDATDIR}/sidads.colorado.edu/pub/DATASETS/NOAA/G02202_v2/seaice_conc_ymonmean_1994-2013.ORCA1.nc
+export NN_ICEF_CLIM="seaice_conc_monthly_cdr"
+
+
+# A text file where the vertical hydraugraphical sections of interest are defined :
+#export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_${CONF}_light.dat"
+export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA1.dat"
+
+# For transport by sigma-class:
+export DENSITY_SECTION_FILE="${BARAKUDA_ROOT}/data/dens_section_ORCA1.dat"
+
+
+# In what directory of the local machine to save the diagnostics:
+export DIAG_DIR="/lustre/tmp/${USER}/barakuda/${CONF}"
+
+
+# Files with the list of rectangular boxes to look at more closely:
+export FILE_DEF_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA1.txt"
+
+
+
+# About remote HOST to install HTML pages to:
+ihttp=0 ; # do we export on a remote http server (1) or keep on the local machine (0)
+RHOST=misu228.misu.su.se ; # remote host to send diagnostic page to///
+RUSER=laurent ; # username associated to remote host (for file export)
+RWWWD=/data/www/barakuda/${CONF} ; # directory of the local or remote host to send the diagnostic page to
+
+
+
+
+#########################
+# Diags to be performed #
+#########################
+
+
+
+
+
+# Basic 3D and surface averages:
+i_do_mean=1
+
+# AMOC:
+i_do_amoc=1
+export LMOCLAT="20-23 30-33 40-43 45-48 50-53" ; # List of latitude bands to look in for max of AMOC
+
+
+# Transport of mass, heat and salt through specified sections (into TRANSPORT_SECTION_FILE):
+i_do_trsp=2  ; # transport of mass, heat and salt through specified sections
+#              # i_do_trsp=2 => treat also different depths range!
+z1_trsp=100  ; # first  depth: i_do_trsp must be set to 2
+z2_trsp=1000 ; # second depth: i_do_trsp must be set to 2
+
+
+# meridional heat/salt transport (advective)
+i_do_mht=1
+
+# Transport by sigma class
+i_do_sigt=1
+
+# sea-ice diags
+i_do_ice=1  ; # Sea-ice diags
+export FILE_ICE_SUFFIX="icemod" ; # in what file to find ice fraction NN_ICEF? => "icemod" or "grid_T"
+
+
+i_do_bb=1   ; # Budget and other stuffs on a given rectangular box!
+#             # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t)  (mean of 2D fields)
+
+
+i_do_ssx_box=0 ; # zoom on given boxes (+spatially-averaged values) for surface properties
+#                # boxes defined into barakuda_orca.py ...
+
+
+# Vertical profiles on of box-averaged as a function of time...
+i_do_box_TS_z=1 ; # do sigma vert. profiles on given boxes... # 1 => no figures, 2 => figures
+#                 # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t,z)
+
+# 
+# Deep Mixed volume in prescribed boxes:
+i_do_dmv=1
+export MLD_CRIT="1000,725,500"
+
+
+
+
+# Some nerdy stuffs about the critical depth in prescribed boxes: 
+i_do_zcrit=0
+
+
+
+
+
+
+# BETA / TESTING:
+
+# Fresh-water transport associated to sea-ice transport
+#  => must compile cdficeflux.x but depends on more recent CDFTOOLS module...
+i_do_icet=0 ; # treat sea-ice volume transport!
+export TRANSPORT_ICE_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA1_ARCTIC.dat"
+
+
+
+
+i_do_flx=0  ; # surface fluxes diags
+
+
+
+
+i_do_amo=0 ;  # buit a SST time serie usable to build Atlantic Multidecadal Oscilation index
+
+
+i_do_sect=0 ; # do sigma vert. profiles on given boxes...
+VSECT_NM=( "Indian_77p5_E" "Atlantic_21p5_W" )
+VSECT_JI=(      "5,5"          "266,266"     ) ; # X range in C convention
+VSECT_JJ=(    "25,170"          "7,291"      ) ; # Y range in C convention

+ 228 - 0
configs/config_ORCA1_L75_T255_ece32_marenostrum.sh

@@ -0,0 +1,228 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for NEMO v3.6 of EC-Earth 3.2 beta tunning on 75 levels
+#
+#            Machine: MareNostrum@BSC
+#
+#        L. Brodeau, November 2016
+#
+#===========================================================
+
+export CONF=ORCA1.L75 ; # horizontal global ORCA configuration
+export NBL=75         ; # number of levels
+
+export HOST=MARENOSTRUM ; # this has no importance at all, it will just become an "info" on the web-page!
+export EXTRA_CONF="NEMO 3.6 + LIM 3 (EC-Earth 3.2b_tuning)" ;   #  // same here ...
+
+# File system / path on which most netcdf data will be read:
+export STORE_DIR="/gpfs/scratch/bsc32/bsc32325"
+
+# Path to directory containing some 2D and 3D climatologies on the relevant ORCA grid:
+export CONF_INI_DIR="/gpfs/projects/bsc32/bsc32325/ORCA1/ORCA1-I/barakuda_clim"
+
+# In what directory of the local machine to save the diagnostics:
+export DIAG_DIR="${STORE_DIR}/barakuda/${CONF}_ece32"
+
+# --- only for problematic hosts ----
+module add NCO/4.2.3    
+module add PYTHON/2.7.3
+# -----------------------------------
+
+export PYTHON_HOME="/apps/PYTHON/2.7.3" ; # HOME to python distribution with matplotlib and basemap !
+
+
+# Is it an ec-earth run?
+export ece_run=2 ; # 0 => not an EC-Earth run, it's a "pure" ocean-only NEMO run done from traditional NEMO setup
+#                  # 1 => it's an OCEAN-ONLY EC-Earth run done from a EC-Earth setup
+#                  # 2 => it's a  COUPLED  EC-Earth run
+#                  #      Both 1 and 2 imply that NEMO files are stored in something like
+#                  #       ${STORE_DIR}/<RUN>/output/nemo/<YYY>
+#                  #       where YYY starts from '001' to
+#                  #   If you select '2', make sure 'cdo' is available and working!!!
+#
+export Y_INI_EC=1990 ;    # initial year if ec-earth run...
+export TRES_IFS=255  ;    # spectral resolution for IFS, ex: T255 => TRES_IFS=255
+###--- end EC-Earth IFS relate section ---
+
+export ATMO_INFO="IFS T${TRES_IFS}" ; # Name of atmospheric model or forcing used (ex: COREv2, DFS5.2, IFS T255, ect...)
+
+# List of suffixed of files that have been saved by NEMO and that are needed for the diags:
+export NEMO_SAVED_FILES="grid_T grid_U grid_V icemod SBC"
+
+# Directory structure in which to find NEMO output file (use <ORCA> and <RUN>):
+export NEMO_OUT_STRCT="${STORE_DIR}/run_ece/<RUN>/output/nemo"
+
+export TSTAMP="1m"   ; # output time-frequency stamp as in NEMO output files...
+
+# How does the nemo files prefix looks like
+# Everything before "<year_related_info>_grid_<X>" or "<year_related_info>_icemod"
+# use <ORCA>, <RUN> and <TSTAMP>=>  Ex: export NEMO_FILE_PREFIX="<ORCA>-<RUN>_<TSTAMP>_"
+export NEMO_FILE_PREFIX="<RUN>_<TSTAMP>_"
+# => should get rid of TSTAMP actually...
+
+# Temporary file system (scratch) on which to perform the job you can use <JOB_ID> if scracth depends on JOB ID:
+#export SCRATCH="/scratch/local/<JOB_ID>" ; # triolith
+export SCRATCH="/scratch/tmp"
+
+
+####### NEMO => what fields in what files ??? ############
+#       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#   => depends on the XIOS *.xml setup you used...
+#   => always specify a string for the NN_* variables
+#      even when missing from your files (ex: NN_MLD="xx")
+#
+# State variables and others in grid_T files:
+export NN_SST="sosstsst"
+export NN_SSS="sosaline"
+export NN_SSH="sossheig"
+export NN_T="votemper"
+export NN_S="vosaline"
+export NN_MLD="mldr10_1"
+#
+# State variables and others in grid_U files:
+export NN_U="vozocrtx"
+export NN_TAUX="sozotaux"
+export NN_U_EIV="0" ; # 0 => ignore
+# State variables and others in grid_V files:
+export NN_V="vomecrty"
+export NN_TAUY="sometauy"
+export NN_V_EIV="0" ; # 0 => ignore
+#
+# Sea-ice fields:
+export FILE_ICE_SUFFIX="icemod" ; # in what file type extension to find ice fields
+export NN_ICEF="siconc" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="sivolu" ; # ice thickness or rather volume...
+#
+# Surface fluxes:
+export FILE_FLX_SUFFIX="SBC" ; # in what file type extension to find surface fluxes
+export NN_FWF="empmr"        ; # name of net freshwater flux (E-P-R) in "FILE_FLX_SUFFIX" file...
+export NN_EMP="emp_oce"      ; # name of E-P in "FILE_FLX_SUFFIX" file...
+export NN_P="precip"         ; # name of total precipitation (solid+liquid) in "FILE_FLX_SUFFIX" file...
+export NN_RNF="runoffs"      ; # name of continental runoffs in "FILE_FLX_SUFFIX" file...
+export NN_CLV="calving"      ; # calving from icebergs in "FILE_FLX_SUFFIX" file...
+export NN_E="evapo"          ; # name of total evaporation in "FILE_FLX_SUFFIX" file...
+export NN_QNET="qt"          ; # name of total net surface heat flux in "FILE_FLX_SUFFIX" file...
+export NN_QSOL="qsr"         ; # name of net surface solar flux in "FILE_FLX_SUFFIX" file...
+#
+################################################################################################
+
+# Land-sea mask and basins files:
+export MM_FILE=/gpfs/projects/bsc32/bsc32325/ORCA1/ec-earth3.2/mesh_mask.nc4
+export BM_FILE=/gpfs/projects/bsc32/bsc32325/ORCA1/ec-earth3.2/basin_mask.nc4
+
+# 3D monthly climatologies of potential temperature and salinity (can be those you used for the NEMO run):
+export F_T_CLIM_3D_12=${CONF_INI_DIR}/thetao_1degx1deg-ORCA1.L75_WOA2009_monthly_LB_20160223.nc4
+export F_S_CLIM_3D_12=${CONF_INI_DIR}/so_1degx1deg-ORCA1.L75_WOA2009_monthly_LB_20160223.nc4
+export SST_CLIM_12=${CONF_INI_DIR}/tos_180x360-ORCA1_Reynolds_monthly_mean1982-2005.nc4
+export NN_T_CLIM="thetao"
+export NN_S_CLIM="so"
+export NN_SST_CLIM="tos"
+
+export ICE_CLIM_12=${CONF_INI_DIR}/ice_cover_180x360-ORCA1_Hurrell_monthly_mean1980-1999.nc4
+export NN_ICEF_CLIM="ice_cover"
+
+
+# A text file where the cross sections (to compute transports) are defined :
+export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA1.dat"
+
+# For transport by sigma-class:
+export DENSITY_SECTION_FILE="${BARAKUDA_ROOT}/data/dens_section_ORCA1.dat"
+
+# Files with the list of rectangular domains to "analyze" more closely:
+export FILE_DEF_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA1.txt"
+export FILE_DMV_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA1.txt"
+
+# In what format should figures be produced ('png' recommanded, 'svg' works):
+export FIG_FORM="png"
+
+# About remote HOST to send/install HTML pages to:
+export ihttp=0                  ; # do we export on a remote http server (1) or keep on the local machine (0)
+export RHOST=whitehouse.gov.org ; # remote host to send diagnostic page to///
+export RUSER=donald             ; # username associated to remote host (for file export)
+export RWWWD=/data/www/barakuda/ec-earth_3.2b ; # directory of the local or remote host to send the diagnostic page to
+
+
+
+#########################
+# Diags to be performed #
+#########################
+
+# Movies of SST and SSS compared to OBS:
+export i_do_movi=1
+
+# Basic 3D and surface averages:
+export i_do_mean=1
+
+# IFS surface fluxes of heat and freshwater
+export i_do_ifs_flx=1 ; # only relevant when ece_run=2...
+
+# AMOC:
+export i_do_amoc=1
+export LMOCLAT="20-23 30-33 40-43 45-48 50-53" ; # List of latitude bands to look in for max of AMOC
+
+# Transport of mass, heat and salt through specified sections (into TRANSPORT_SECTION_FILE):
+export i_do_trsp=1  ; # transport of mass, heat and salt through specified sections
+#              # i_do_trsp=2 => treat also different depths range!
+z1_trsp=100  ; # first  depth: i_do_trsp must be set to 2
+z2_trsp=1000 ; # second depth: i_do_trsp must be set to 2
+
+# Meridional heat/salt transport (advective)
+export i_do_mht=1
+
+# Transport by sigma class
+export i_do_sigt=1
+
+# Sea-ice diags
+export i_do_ice=1  ; # Sea-ice diags
+
+# Budget on pre-defined (FILE_DEF_BOXES) rectangular domains:
+export i_do_bb=1   ; # Budget and other stuffs on a given rectangular box!
+#             # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t)  (mean of 2D fields)
+
+# Vertical profiles on of box-averaged as a function of time...
+export i_do_box_TS_z=1 ; # do sigma vert. profiles on given boxes... # 1 => no figures, 2 => figures
+#                 # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t,z)
+
+# Deep Mixed volume in prescribed boxes:
+export i_do_dmv=0
+export MLD_CRIT="1000,725,500"
+
+# User-defined meridional or zonal cross sections (for temperature and salinity)
+# => TS_SECTION_FILE must be defined!
+export i_do_sect=1
+export TS_SECTION_FILE="${BARAKUDA_ROOT}/data/TS_sections.dat"
+
+
+
+# BETA / TESTING / NERDY (at your own risks...):
+#
+export i_do_ssx_box=0 ; # zoom on given boxes (+spatially-averaged values) for surface properties
+#                     # boxes defined into barakuda_orca.py ...
+
+# Some nerdy stuffs about the critical depth in prescribed boxes:
+export i_do_zcrit=0
+
+# Fresh-water transport associated to sea-ice transport
+#  => must compile cdficeflux.x but depends on more recent CDFTOOLS module...
+export i_do_icet=0 ; # treat sea-ice volume transport!
+export TRANSPORT_ICE_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA1_ARCTIC.dat"
+
+export i_do_amo=0 ;  # buit a SST time serie usable to build Atlantic Multidecadal Oscilation index
+
+
+
+
+# Place for potential specific host-related survival tricks:
+
+#========================== Marenostrum @ BSC =========================================================
+### Shouldn't be needed elsewhere than MareNostrum, where it's a hello to have CDO working...
+## => Only if you specified ece_run=2 and i_do_ifs_flx
+export MOD_CDO="gcc/4.7.2 intel/13.0.1 openmpi/1.8.1 NETCDF/4.1.3 HDF5/1.8.10 UDUNITS/2.1.24 CDO/1.7.0"
+#=======================================================================================================
+

+ 234 - 0
configs/config_ORCA1_L75_T255_ece32_triolith.sh

@@ -0,0 +1,234 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for NEMO v3.6 of EC-Earth 3.2.2 on 75 levels
+#
+#        Machine: triolith.nsc.liu.se
+#
+#        L. Brodeau, 2017
+#
+#===========================================================
+
+export CONF=ORCA1.L75 ; # horizontal global ORCA configuration
+export NBL=75         ; # number of levels
+
+export HOST=TRIOLITH.nsc.liu.se ; # this has no importance at all, it will just become an "info" on the web-page!
+export MASTERMIND="BSC / Laurent" ; # same here, who's the person who designed/ran this simulation?
+
+export EXTRA_CONF="NEMO 3.6 + LIM 3 (EC-Earth 3.2.2)" ;   #  // same here ...
+
+# Path / directory structure in which to find NEMO output file (you can use
+# <ORCA> and <EXP> as substitute to your ORCA grid and experiment (EXP) name):
+export NEMO_OUT_STRCT="/proj/bolinc/users/x_laubr/run/<EXP>/output/nemo"
+
+# Path to root directory where to save the diagnostics (diagnostics for this "CONF"):
+export DIAG_DIR="/proj/bolinc/users/x_laubr/barakuda/ece32"
+
+# Path to directory containing some 2D and 3D climatologies on the relevant ORCA grid:
+export CONF_INI_DIR="/proj/bolinc/users/x_laubr/input_barakuda/ORCA1.L75_barakuda"
+
+# Temporary file system (scratch) on which to perform the job you can use <JOB_ID> if scracth depends on JOB ID:
+export SCRATCH="/scratch/local/<JOB_ID>"
+
+export PYTHON_HOME="/home/x_laubr/opt/Canopy_64bit/User" ; # HOME to python distribution with matplotlib and basemap !
+
+export DIR_NCVIEW_CMAP="${BARAKUDA_ROOT}/src/ncview_colormaps"
+
+# Is it an ec-earth experiment?
+export ece_exp=2 ; # 0 => not an EC-Earth experiment, it's a "pure" ocean-only NEMO experiment done from traditional NEMO setup
+#                  # 1 => it's an OCEAN-ONLY EC-Earth experiment done from a EC-Earth setup
+#                  # 2 => it's a  COUPLED  EC-Earth experiment
+#                  #      Both 1 and 2 imply that NEMO files are stored in something like
+#                  #       ${SOMEWHERE}/<EXP>/output/nemo/<YYY>
+#                  #       where YYY starts from '001' to
+#                  #      If you select '2', make sure 'cdo' is available and working!!!
+#                  # 10 => this experiment controled by AutoSubmit (so NEMO files are tared somerwhere?)
+#
+export Y_INI_EC=1990 ;    # initial year if ece_exp /= 0 !!!
+export M_INI_EC="01" ;    # initial month, only needed if ece_exp >= 10 !!!
+export NCHNKS_Y=1    ;    # number of chunks per year if ece_exp >= 10 (only needed if NCHNKS_Y >= 2 !)
+export TRES_IFS=255  ;    # spectral resolution for IFS, ex: T255 => TRES_IFS=255
+###--- end EC-Earth IFS relate section ---
+
+export ATMO_INFO="IFS T${TRES_IFS}" ; # Name of atmospheric model or forcing used (ex: COREv2, DFS5.2, IFS T255, ect...)
+
+# List of suffix of files that have been saved by NEMO and contain MONTHLY averages:
+export NEMO_SAVED_FILES="grid_T grid_U grid_V icemod SBC"
+
+export TSTAMP="1m"   ; # output time-frequency stamp as in NEMO output files...
+
+# In case 3D fields have been saved on an annual mean basis rather than montly:
+export ANNUAL_3D="" ;   # leave blanck "" if 3D fields are in monthly files...
+export NEMO_SAVED_FILES_3D="" ; #     ''
+
+# How does the nemo files prefix looks like
+# Everything before "<year_related_info>_grid_<X>" or "<year_related_info>_icemod"
+# use <ORCA>, <EXP> and <TSTAMP>=>  Ex: export NEMO_FILE_PREFIX="<ORCA>-<EXP>_<TSTAMP>_"
+export NEMO_FILE_PREFIX="<EXP>_<TSTAMP>_"
+# => should get rid of TSTAMP actually...
+
+
+####### NEMO => what fields in what files ??? ############
+#       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#   => depends on the XIOS *.xml setup you used...
+#   => always specify a string for the NN_* variables
+#      USE "X" if the field is not present in your NEMO output
+#
+# State variables and others in grid_T files:
+export NN_SST="tos"
+export NN_SSS="sos"
+export NN_SSH="zos"
+export NN_T="thetao"
+export NN_S="so"
+export NN_MLD="mldr10_1"
+#
+# State variables and others in grid_U files:
+export NN_U="uo"
+export NN_TAUX="tauuo"
+export NN_U_EIV="0" ; # 0 => ignore
+# State variables and others in grid_V files:
+export NN_V="vo"
+export NN_TAUY="tauvo"
+export NN_V_EIV="0" ; # 0 => ignore
+#
+# Sea-ice fields:
+export FILE_ICE_SUFFIX="icemod" ; # in what file type extension to find ice fields
+export NN_ICEF="siconc" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="sivolu" ; # ice thickness or rather volume...
+export NN_ICEU="sivelu" ; # ice U-velocity
+export NN_ICEV="sivelv" ; # ice V-velocity
+#
+# Surface fluxes:
+export FILE_FLX_SUFFIX="SBC" ; # in what file type extension to find surface fluxes (normally: "SBC")
+####                           # => mind that $FILE_FLX_SUFFIX must be also in NEMO_SAVED_FILES (above)
+#### Note: in fields marked with *+/-* you can use a sum or substraction of variables (no space allowed!)
+####       ex: NN_EMP="evap_ao_cea+subl_ai_cea-precip"
+####           NN_QNET="qsr+qnsol"
+# ++ Surface freswater fluxes:
+export NN_FWF="wfo"       ; # *+/-* name of net freshwater flux (E-P-R) in "FILE_FLX_SUFFIX" file...
+export NN_EMP="evap_ao_cea+subl_ai_cea-precip" ; # *+/-* name of E-P in "FILE_FLX_SUFFIX" file...
+export NN_P="precip"      ; # name of total precipitation (solid+liquid) in "FILE_FLX_SUFFIX" file...
+export NN_RNF="runoffs"   ; # name of continental runoffs in "FILE_FLX_SUFFIX" file...
+export NN_CLV="calving"   ; # calving from icebergs in "FILE_FLX_SUFFIX" file...
+export NN_E="evap_ao_cea+subl_ai_cea" ; # *+/-* name of total evaporation in "FILE_FLX_SUFFIX" file...
+# ++ Surface heat fluxes:
+export NN_QNET="qt_oce"   ; # *+/-* name of total net surface heat flux in "FILE_FLX_SUFFIX" file...
+export NN_QSOL="rsntds"   ; # name of net surface solar flux in "FILE_FLX_SUFFIX" file...
+# ++ Wind-stress module:
+export NN_TAUM="taum"        ; # name of surface wind stress module in "FILE_FLX_SUFFIX" file...
+export NN_WNDM="windsp"      ; # name of surface wind  speed module in "FILE_FLX_SUFFIX" file...
+#
+################################################################################################
+
+# Land-sea mask and basins files:
+export MM_FILE=${CONF_INI_DIR}/mesh_mask.nc4
+export BM_FILE=${BARAKUDA_ROOT}/data/basin_mask_ORCA1_ece3.2_2017.nc4
+
+# OBSERVATIONS / REFERENCES
+# 3D monthly climatologies of potential temperature and salinity (can be those you used for the NEMO experiment):
+export NM_TS_OBS="EN4.2.0 [1990-2010]"
+export F_T_OBS_3D_12=${CONF_INI_DIR}/thetao_EN.4.2.0_ORCA1L75_mclim_1990-2010.nc4
+export F_S_OBS_3D_12=${CONF_INI_DIR}/so_EN.4.2.0_ORCA1L75_mclim_1990-2010.nc4
+export F_SST_OBS_12=${CONF_INI_DIR}/thetao_EN.4.2.0_ORCA1L75_mclim_1990-2010.nc4
+export NN_T_OBS="thetao"
+export NN_S_OBS="so"
+export NN_SST_OBS="thetao"
+#
+# Sea-ice:
+export NM_IC_OBS="Hurrell et al 2008 [1980-1999]"
+export F_ICE_OBS_12=${CONF_INI_DIR}/ice_cover_180x360-ORCA1_Hurrell_monthly_mean1980-1999.nc4
+export NN_ICEF_OBS="ice_cover"
+#
+# Surface Heat fluxes:
+export NM_QSOL_OBS="NOCS 2.0 [1980-2005]"
+export F_QSOL_OBS_12=${BARAKUDA_ROOT}/data/obs/radsw_monthly_clim_1980-2005_NOCS2.nc4
+export NN_QSOL_OBS="radsw"
+
+
+# A text file where the cross sections (to compute transports) are defined :
+export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA1.dat"        ; # set i_do_trsp=1 !
+export TRANSPORT_SECTION_FILE_ICE="${BARAKUDA_ROOT}/data/transport_ice_ORCA1.dat"  ; # set i_do_trsp_ice=1 !
+
+# For transport by sigma-class:
+export DENSITY_SECTION_FILE="${BARAKUDA_ROOT}/data/dens_section_ORCA1.dat"
+
+# Files with the list of rectangular domains to "analyze" more closely:
+export FILE_DEF_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA1.txt"
+export FILE_DMV_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA1.txt"
+
+# In what format should figures be produced ('png' recommanded, but 'svg' supported!):
+export FIG_FORM="png"
+
+# About remote HOST to send/install HTML pages to:
+export ihttp=0                ; # do we export on a remote http server (1) or keep on the local machine (0)
+export RHOST=whitehouse.gov   ; # remote host to send diagnostic page to///
+export RUSER=donald           ; # username associated to remote host (for file export)
+export RWWWD=/data/www/barakuda/ec-earth_3.2b ; # directory of the local or remote host to send the diagnostic page to
+
+
+#########################
+# Diags to be performed #
+#########################
+
+# Movies of SST and SSS compared to OBS:
+export i_do_movi=1
+export iffmpeg_x264=0 ; # is, by chance, ffmpeg with support for x264 encoding available on your stystem? => 1 !
+
+# Basic 3D and surface averages:
+export i_do_mean=1
+
+# IFS surface fluxes of heat and freshwater
+export i_do_ifs_flx=1 ; # only relevant when ece_exp=2...
+
+# AMOC:
+export i_do_amoc=1
+export LMOCLAT="20-23 30-33 40-43 45-48 50-53" ; # List of latitude bands to look in for max of AMOC
+
+# Sea-ice diags
+export i_do_ice=1  ; # Sea-ice diags
+
+# Transport of mass, heat and salt through specified sections (into TRANSPORT_SECTION_FILE):
+export i_do_trsp=1  ; # transport of mass, heat and salt through specified sections
+#              # i_do_trsp=2 => treat also different depths range!
+z1_trsp=100  ; # first  depth: i_do_trsp must be set to 2
+z2_trsp=1000 ; # second depth: i_do_trsp must be set to 2
+
+# Solid freshwater transport through sections due to sea-ice drift
+export i_do_trsp_ice=1 ; # must have i_do_ice=1
+
+# Meridional heat/salt transport (advective)
+export i_do_mht=1
+
+# Transport by sigma class
+export i_do_sigt=1
+
+# Budget on pre-defined (FILE_DEF_BOXES) rectangular domains:
+export i_do_bb=0   ; # Budget and other stuffs on a given rectangular box!
+#             # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t)  (mean of 2D fields)
+
+# Vertical profiles on of box-averaged as a function of time...
+export i_do_box_TS_z=0 ; # do sigma vert. profiles on given boxes... # 1 => no figures, 2 => figures
+#                 # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t,z)
+
+# Deep Mixed volume in prescribed boxes:
+export i_do_dmv=0
+export MLD_CRIT="1000,725,500"
+
+# User-defined meridional or zonal cross sections (for temperature and salinity)
+# => TS_SECTION_FILE must be defined!
+export i_do_sect=1
+export TS_SECTION_FILE="${BARAKUDA_ROOT}/data/TS_sections.dat"
+
+
+# BETA / TESTING / NERDY (at your own risks...):
+#
+export i_do_ssx_box=0 ; # zoom on given boxes (+spatially-averaged values) for surface properties
+#                     # boxes defined into barakuda_orca.py ...
+
+# Some nerdy stuffs about the critical depth in prescribed boxes:
+export i_do_zcrit=0

+ 221 - 0
configs/config_ORCA1_L75_T255_ece32_zenobe.sh

@@ -0,0 +1,221 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for NEMO v3.6 of EC-Earth 3.2.2 on 75 levels
+#
+#        Machine: zenobe@cenaero
+#
+#        F.Massonnet, 2017
+#
+#===========================================================
+
+export CONF=ORCA1.L75 ; # horizontal global ORCA configuration
+export NBL=75         ; # number of levels
+
+export HOST=ZENOBE ; # this has no importance at all, it will just become an "info" on the web-page!
+export MASTERMIND="UCL / $USER" ; # same here, who's the person who designed/ran this simulation?
+
+export EXTRA_CONF="NEMO 3.6 + LIM 3 (EC-Earth 3.2)" ;   #  // same here ...
+
+# Path / directory structure in which to find NEMO output file (you can use
+# <ORCA> and <EXP> as substitute to your ORCA grid and experiment (EXP) name):
+export NEMO_OUT_STRCT="/SCRATCH/acad/ecearth/${USER}/run/<EXP>/output/nemo"
+
+# Path to root directory where to save the diagnostics (diagnostics for this "CONF"):
+export DIAG_DIR="/SCRATCH/acad/ecearth/${USER}/barakuda/${CONF}_ece32"
+
+# Path to directory containing some 2D and 3D climatologies on the relevant ORCA grid:
+export CONF_INI_DIR="/home/acad/ucl-elic/fmasson/ec-earth3.2_config_files/barakuda_clim/"
+
+# Temporary file system (scratch) on which to perform the job you can use <JOB_ID> if scracth depends on JOB ID:
+export SCRATCH="/SCRATCH/acad/ecearth/${USER}/TMP/"
+
+export PYTHON_HOME="/projects/acad/ecearth/opt/software/Python/2.7.12-foss-2016b/" ; # HOME to python distribution with matplotlib and basemap !
+
+export DIR_NCVIEW_CMAP="${BARAKUDA_ROOT}/src/ncview_colormaps"
+
+# Is it an ec-earth experiment?
+export ece_exp=2 ; # 0 => not an EC-Earth experiment, it's a "pure" ocean-only NEMO experiment done from traditional NEMO setup
+#                  # 1 => it's an OCEAN-ONLY EC-Earth experiment done from a EC-Earth setup
+#                  # 2 => it's a  COUPLED  EC-Earth experiment
+#                  #      Both 1 and 2 imply that NEMO files are stored in something like
+#                  #       ${SOMEWHERE}/<EXP>/output/nemo/<YYY>
+#                  #       where YYY starts from '001' to
+#                  #      If you select '2', make sure 'cdo' is available and working!!!
+#                  # 10 => this experiment controled by AutoSubmit (so NEMO files are tared somerwhere?)
+#
+export Y_INI_EC=1990 ;    # initial year if ece_exp /= 0 !!!
+export TRES_IFS=255  ;    # spectral resolution for IFS, ex: T255 => TRES_IFS=255
+###--- end EC-Earth IFS relate section ---
+
+export ATMO_INFO="IFS T${TRES_IFS}" ; # Name of atmospheric model or forcing used (ex: COREv2, DFS5.2, IFS T255, ect...)
+
+# List of suffix of files that have been saved by NEMO and contain MONTHLY averages:
+export NEMO_SAVED_FILES="grid_T grid_U grid_V icemod SBC"
+
+export TSTAMP="1m"   ; # output time-frequency stamp as in NEMO output files...
+
+# In case 3D fields have been saved on an annual mean basis rather than montly:
+export ANNUAL_3D="" ;   # leave blanck "" if 3D fields are in monthly files...
+export NEMO_SAVED_FILES_3D="" ; #     ''
+
+# How does the nemo files prefix looks like
+# Everything before "<year_related_info>_grid_<X>" or "<year_related_info>_icemod"
+# use <ORCA>, <EXP> and <TSTAMP>=>  Ex: export NEMO_FILE_PREFIX="<ORCA>-<EXP>_<TSTAMP>_"
+export NEMO_FILE_PREFIX="<EXP>_<TSTAMP>_"
+# => should get rid of TSTAMP actually...
+
+
+####### NEMO => what fields in what files ??? ############
+#       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#   => depends on the XIOS *.xml setup you used...
+#   => always specify a string for the NN_* variables
+#      USE "X" if the field is not present in your NEMO output
+#
+# State variables and others in grid_T files:
+export NN_SST="tos"
+export NN_SSS="sos"
+export NN_SSH="zos"
+export NN_T="thetao"
+export NN_S="so"
+export NN_MLD="mldr10_1"
+#
+# State variables and others in grid_U files:
+export NN_U="uo"
+export NN_TAUX="tauuo"
+export NN_U_EIV="0" ; # 0 => ignore
+# State variables and others in grid_V files:
+export NN_V="vo"
+export NN_TAUY="tauvo"
+export NN_V_EIV="0" ; # 0 => ignore
+#
+# Sea-ice fields:
+export FILE_ICE_SUFFIX="icemod" ; # in what file type extension to find ice fields
+export NN_ICEF="siconc" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="sivolu" ; # ice thickness or rather volume...
+export NN_ICEU="sivelu" ; # ice U-velocity
+export NN_ICEV="sivelv" ; # ice V-velocity
+#
+# Surface fluxes:
+export FILE_FLX_SUFFIX="SBC" ; # in what file type extension to find surface fluxes
+# ++ Surface freswater fluxes:
+export NN_FWF="wfo"       ; # *+/-* name of net freshwater flux (E-P-R) in "FILE_FLX_SUFFIX" file...
+export NN_EMP="evap_ao_cea+subl_ai_cea-precip" ; # *+/-* name of E-P in "FILE_FLX_SUFFIX" file...
+export NN_P="precip"      ; # name of total precipitation (solid+liquid) in "FILE_FLX_SUFFIX" file...
+export NN_RNF="runoffs"   ; # name of continental runoffs in "FILE_FLX_SUFFIX" file...
+export NN_CLV="calving"   ; # calving from icebergs in "FILE_FLX_SUFFIX" file...
+export NN_E="evap_ao_cea+subl_ai_cea" ; # *+/-* name of total evaporation in "FILE_FLX_SUFFIX" file...
+# ++ Surface heat fluxes:
+export NN_QNET="qt_oce"   ; # *+/-* name of total net surface heat flux in "FILE_FLX_SUFFIX" file...
+export NN_QSOL="rsntds"   ; # name of net surface solar flux in "FILE_FLX_SUFFIX" file...
+# ++ Wind-stress module:
+export NN_TAUM="taum"        ; # name of surface wind stress module in "FILE_FLX_SUFFIX" file...
+export NN_WNDM="windsp"      ; # name of surface wind  speed module in "FILE_FLX_SUFFIX" file...
+#
+################################################################################################
+
+# Land-sea mask and basins files:
+export MM_FILE=/home/acad/ucl-elic/fmasson/ec-earth3.2_config_files/mesh_mask.nc4
+export BM_FILE=${BARAKUDA_ROOT}/data/basin_mask_ORCA1_ece3.2_2017.nc4
+
+# OBSERVATIONS / REFERENCES
+# 3D monthly climatologies of potential temperature and salinity (can be those you used for the NEMO experiment):
+export NM_TS_OBS="EN4.2.0 [1990-2010]"
+export F_T_OBS_3D_12=${CONF_INI_DIR}/thetao_1degx1deg-ORCA1.L75_WOA2009_monthly_LB_20160223.nc4
+export F_S_OBS_3D_12=${CONF_INI_DIR}/so_1degx1deg-ORCA1.L75_WOA2009_monthly_LB_20160223.nc4
+export F_SST_OBS_12=${CONF_INI_DIR}/tos_180x360-ORCA1_Reynolds_monthly_mean1982-2005.nc4
+export NN_T_OBS="thetao"
+export NN_S_OBS="so"
+export NN_SST_OBS="tos"
+
+export F_ICE_OBS_12=${CONF_INI_DIR}/ice_cover_180x360-ORCA1_Hurrell_monthly_mean1980-1999.nc4
+export NN_ICEF_OBS="ice_cover"
+
+
+# A text file where the cross sections (to compute transports) are defined :
+export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA1.dat"        ; # set i_do_trsp=1 !
+export TRANSPORT_SECTION_FILE_ICE="${BARAKUDA_ROOT}/data/transport_ice_ORCA1.dat"  ; # set i_do_trsp_ice=1 !
+
+# For transport by sigma-class:
+export DENSITY_SECTION_FILE="${BARAKUDA_ROOT}/data/dens_section_ORCA1.dat"
+
+# Files with the list of rectangular domains to "analyze" more closely:
+export FILE_DEF_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA1.txt"
+export FILE_DMV_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA1.txt"
+
+# In what format should figures be produced ('png' recommanded, but 'svg' supported!):
+export FIG_FORM="png"
+
+# About remote HOST to send/install HTML pages to:
+export ihttp=1                ; # do we export on a remote http server (1) or keep on the local machine (0)
+export RHOST=elixir%gwelic   ; # remote host to send diagnostic page to///
+export RUSER=$USER           ; # username associated to remote host (for file export)
+export RWWWD=/elic/ftp/$USER/TMP/ ; # directory of the local or remote host to send the diagnostic page to
+
+
+#########################
+# Diags to be performed #
+#########################
+
+# Movies of SST and SSS compared to OBS:
+export i_do_movi=1
+export iffmpeg_x264=0 ; # is, by chance, ffmpeg with support for x264 encoding available on your stystem? => 1 !
+
+# Basic 3D and surface averages:
+export i_do_mean=1
+
+# IFS surface fluxes of heat and freshwater
+export i_do_ifs_flx=1 ; # only relevant when ece_exp=2...
+
+# AMOC:
+export i_do_amoc=1
+export LMOCLAT="20-23 30-33 40-43 45-48 50-53" ; # List of latitude bands to look in for max of AMOC
+
+# Sea-ice diags
+export i_do_ice=1  ; # Sea-ice diags
+
+# Transport of mass, heat and salt through specified sections (into TRANSPORT_SECTION_FILE):
+export i_do_trsp=1  ; # transport of mass, heat and salt through specified sections
+#              # i_do_trsp=2 => treat also different depths range!
+z1_trsp=100  ; # first  depth: i_do_trsp must be set to 2
+z2_trsp=1000 ; # second depth: i_do_trsp must be set to 2
+
+# Solid freshwater transport through sections due to sea-ice drift
+export i_do_trsp_ice=1 ; # must have i_do_ice=1
+
+# Meridional heat/salt transport (advective)
+export i_do_mht=1
+
+# Transport by sigma class
+export i_do_sigt=1
+
+# Budget on pre-defined (FILE_DEF_BOXES) rectangular domains:
+export i_do_bb=0   ; # Budget and other stuffs on a given rectangular box!
+#             # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t)  (mean of 2D fields)
+
+# Vertical profiles on of box-averaged as a function of time...
+export i_do_box_TS_z=0 ; # do sigma vert. profiles on given boxes... # 1 => no figures, 2 => figures
+#                 # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t,z)
+
+# Deep Mixed volume in prescribed boxes:
+export i_do_dmv=0
+export MLD_CRIT="1000,725,500"
+
+# User-defined meridional or zonal cross sections (for temperature and salinity)
+# => TS_SECTION_FILE must be defined!
+export i_do_sect=1
+export TS_SECTION_FILE="${BARAKUDA_ROOT}/data/TS_sections.dat"
+
+
+# BETA / TESTING / NERDY (at your own risks...):
+#
+export i_do_ssx_box=0 ; # zoom on given boxes (+spatially-averaged values) for surface properties
+#                     # boxes defined into barakuda_orca.py ...
+
+# Some nerdy stuffs about the critical depth in prescribed boxes:
+export i_do_zcrit=0

+ 1 - 0
configs/config_ORCA1_L75_TEMPLATE.sh

@@ -0,0 +1 @@
+config_ORCA1_L75_T255_ece32_triolith.sh

+ 233 - 0
configs/config_ORCA1_L75_ece32_cca.sh

@@ -0,0 +1,233 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for NEMO v3.6 of EC-Earth 3.2.2 on 75 levels
+#
+#        Machine: cca/ccb ecmwf.int
+#
+#        L. Brodeau, 2017
+#        P. Le Sager, June 27, 2017
+#
+#===========================================================
+
+export CONF=ORCA1.L75 ; # horizontal global ORCA configuration
+export NBL=75         ; # number of levels
+
+export HOST="cca/ECMWF" ; # this has no importance at all, it will just become an "info" on the web-page!
+export MASTERMIND="KNMI / Frank Selten" ; # same here, who's the person who designed/ran this simulation?
+
+export EXTRA_CONF="NEMO 3.6 + LIM 3 (EC-Earth 3.2.2)" ;   #  // same here ...
+
+# Path / directory structure in which to find NEMO output file (you can use
+# <ORCA> and <EXP> as substitute to your ORCA grid and experiment (EXP) name):
+export NEMO_OUT_STRCT="/scratch/ms/nl/ruc/ECEARTH-RUNS/<EXP>/output/nemo"
+
+# Path to root directory where to save the diagnostics (diagnostics for this "CONF"):
+export DIAG_DIR="$SCRATCH/barakuda/ece32"
+
+# Path to directory containing some 2D and 3D climatologies on the relevant ORCA grid:
+export CONF_INI_DIR="/scratch/ms/nl/nm6/ECE-DATA/input_barakuda/ORCA1.L75_barakuda"
+
+# Temporary file system (scratch) on which to perform the job you can use <JOB_ID> if scracth depends on JOB ID:
+export SCRATCH="$SCRATCH"
+
+export PYTHON_HOME="/usr/local/apps/python/2.7.12-01/" ; # HOME to python distribution with matplotlib and basemap !
+
+export DIR_NCVIEW_CMAP="${BARAKUDA_ROOT}/src/ncview_colormaps"
+
+# Is it an ec-earth experiment?
+export ece_exp=2 ; # 0 => not an EC-Earth experiment, it's a "pure" ocean-only NEMO experiment done from traditional NEMO setup
+#                  # 1 => it's an OCEAN-ONLY EC-Earth experiment done from a EC-Earth setup
+#                  # 2 => it's a  COUPLED  EC-Earth experiment
+#                  #      Both 1 and 2 imply that NEMO files are stored in something like
+#                  #       ${SOMEWHERE}/<EXP>/output/nemo/<YYY>
+#                  #       where YYY starts from '001' to
+#                  #      If you select '2', make sure 'cdo' is available and working!!!
+#                  # 10 => this experiment controled by AutoSubmit (so NEMO files are tared somerwhere?)
+#
+export Y_INI_EC=1990 ;    # initial year if ece_exp /= 0 !!!
+export TRES_IFS=255  ;    # spectral resolution for IFS, ex: T255 => TRES_IFS=255
+###--- end EC-Earth IFS relate section ---
+
+export ATMO_INFO="IFS T${TRES_IFS}" ; # Name of atmospheric model or forcing used (ex: COREv2, DFS5.2, IFS T255, ect...)
+
+# List of suffix of files that have been saved by NEMO and contain MONTHLY averages:
+export NEMO_SAVED_FILES="grid_T grid_U grid_V icemod SBC"
+
+export TSTAMP="1m"   ; # output time-frequency stamp as in NEMO output files...
+
+# In case 3D fields have been saved on an annual mean basis rather than montly:
+export ANNUAL_3D="" ;   # leave blanck "" if 3D fields are in monthly files...
+export NEMO_SAVED_FILES_3D="" ; #     ''
+
+# How does the nemo files prefix looks like
+# Everything before "<year_related_info>_grid_<X>" or "<year_related_info>_icemod"
+# use <ORCA>, <EXP> and <TSTAMP>=>  Ex: export NEMO_FILE_PREFIX="<ORCA>-<EXP>_<TSTAMP>_"
+export NEMO_FILE_PREFIX="<EXP>_<TSTAMP>_"
+# => should get rid of TSTAMP actually...
+
+
+####### NEMO => what fields in what files ??? ############
+#       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#   => depends on the XIOS *.xml setup you used...
+#   => always specify a string for the NN_* variables
+#      USE "X" if the field is not present in your NEMO output
+#
+# State variables and others in grid_T files:
+export NN_SST="tos"
+export NN_SSS="sos"
+export NN_SSH="zos"
+export NN_T="thetao"
+export NN_S="so"
+export NN_MLD="mldr10_1"
+#
+# State variables and others in grid_U files:
+export NN_U="uo"
+export NN_TAUX="tauuo"
+export NN_U_EIV="0" ; # 0 => ignore
+# State variables and others in grid_V files:
+export NN_V="vo"
+export NN_TAUY="tauvo"
+export NN_V_EIV="0" ; # 0 => ignore
+#
+# Sea-ice fields:
+export FILE_ICE_SUFFIX="icemod" ; # in what file type extension to find ice fields
+export NN_ICEF="siconc" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="sivolu" ; # ice thickness or rather volume...
+export NN_ICEU="sivelu" ; # ice U-velocity
+export NN_ICEV="sivelv" ; # ice V-velocity
+#
+# Surface fluxes:
+export FILE_FLX_SUFFIX="SBC" ; # in what file type extension to find surface fluxes (normally: "SBC")
+####                           # => mind that $FILE_FLX_SUFFIX must be also in NEMO_SAVED_FILES (above)
+#### Note: in fields marked with *+/-* you can use a sum or substraction of variables (no space allowed!)
+####       ex: NN_EMP="evap_ao_cea+subl_ai_cea-precip"
+####           NN_QNET="qsr+qnsol"
+# ++ Surface freswater fluxes:
+export NN_FWF="wfo"       ; # *+/-* name of net freshwater flux (E-P-R) in "FILE_FLX_SUFFIX" file...
+export NN_EMP="evap_ao_cea+subl_ai_cea-precip" ; # *+/-* name of E-P in "FILE_FLX_SUFFIX" file...
+export NN_P="precip"      ; # name of total precipitation (solid+liquid) in "FILE_FLX_SUFFIX" file...
+export NN_RNF="runoffs"   ; # name of continental runoffs in "FILE_FLX_SUFFIX" file...
+export NN_CLV="calving"   ; # calving from icebergs in "FILE_FLX_SUFFIX" file...
+export NN_E="evap_ao_cea+subl_ai_cea" ; # *+/-* name of total evaporation in "FILE_FLX_SUFFIX" file...
+# ++ Surface heat fluxes:
+export NN_QNET="qt_oce"   ; # *+/-* name of total net surface heat flux in "FILE_FLX_SUFFIX" file...
+export NN_QSOL="rsntds"   ; # name of net surface solar flux in "FILE_FLX_SUFFIX" file...
+# ++ Wind-stress module:
+export NN_TAUM="taum"        ; # name of surface wind stress module in "FILE_FLX_SUFFIX" file...
+export NN_WNDM="windsp"      ; # name of surface wind  speed module in "FILE_FLX_SUFFIX" file...
+#
+################################################################################################
+
+# Land-sea mask and basins files:
+export MM_FILE=${CONF_INI_DIR}/mesh_mask.nc4
+export BM_FILE=${BARAKUDA_ROOT}/data/basin_mask_ORCA1_ece3.2_2017.nc4
+
+# OBSERVATIONS / REFERENCES
+# 3D monthly climatologies of potential temperature and salinity (can be those you used for the NEMO experiment):
+export NM_TS_OBS="EN4.2.0 [1990-2010]"
+export F_T_OBS_3D_12=${CONF_INI_DIR}/thetao_EN.4.2.0_ORCA1L75_mclim_1990-2010.nc4
+export F_S_OBS_3D_12=${CONF_INI_DIR}/so_EN.4.2.0_ORCA1L75_mclim_1990-2010.nc4
+export F_SST_OBS_12=${CONF_INI_DIR}/thetao_EN.4.2.0_ORCA1L75_mclim_1990-2010.nc4
+export NN_T_OBS="thetao"
+export NN_S_OBS="so"
+export NN_SST_OBS="thetao"
+#
+# Sea-ice:
+export NM_IC_OBS="Hurrell et al 2008 [1980-1999]"
+export F_ICE_OBS_12=${CONF_INI_DIR}/ice_cover_180x360-ORCA1_Hurrell_monthly_mean1980-1999.nc4
+export NN_ICEF_OBS="ice_cover"
+#
+# Surface Heat fluxes:
+export NM_QSOL_OBS="NOCS 2.0 [1980-2005]"
+export F_QSOL_OBS_12=${BARAKUDA_ROOT}/data/obs/radsw_monthly_clim_1980-2005_NOCS2.nc4
+export NN_QSOL_OBS="radsw"
+
+
+# A text file where the cross sections (to compute transports) are defined :
+export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA1.dat"        ; # set i_do_trsp=1 !
+export TRANSPORT_SECTION_FILE_ICE="${BARAKUDA_ROOT}/data/transport_ice_ORCA1.dat"  ; # set i_do_trsp_ice=1 !
+
+# For transport by sigma-class:
+export DENSITY_SECTION_FILE="${BARAKUDA_ROOT}/data/dens_section_ORCA1.dat"
+
+# Files with the list of rectangular domains to "analyze" more closely:
+export FILE_DEF_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA1.txt"
+export FILE_DMV_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA1.txt"
+
+# In what format should figures be produced ('png' recommanded, but 'svg' supported!):
+export FIG_FORM="png"
+
+# About remote HOST to send/install HTML pages to:
+export ihttp=0                ; # do we export on a remote http server (1) or keep on the local machine (0)
+export RHOST=whitehouse.gov   ; # remote host to send diagnostic page to///
+export RUSER=donald           ; # username associated to remote host (for file export)
+export RWWWD=/data/www/barakuda/ec-earth_3.2b ; # directory of the local or remote host to send the diagnostic page to
+
+
+#########################
+# Diags to be performed #
+#########################
+
+# Movies of SST and SSS compared to OBS:
+export i_do_movi=1
+export iffmpeg_x264=0 ; # is, by chance, ffmpeg with support for x264 encoding available on your stystem? => 1 !
+
+# Basic 3D and surface averages:
+export i_do_mean=1
+
+# IFS surface fluxes of heat and freshwater
+export i_do_ifs_flx=1 ; # only relevant when ece_exp=2...
+
+# AMOC:
+export i_do_amoc=1
+export LMOCLAT="20-23 30-33 40-43 45-48 50-53" ; # List of latitude bands to look in for max of AMOC
+
+# Sea-ice diags
+export i_do_ice=1  ; # Sea-ice diags
+
+# Transport of mass, heat and salt through specified sections (into TRANSPORT_SECTION_FILE):
+export i_do_trsp=1  ; # transport of mass, heat and salt through specified sections
+#              # i_do_trsp=2 => treat also different depths range!
+z1_trsp=100  ; # first  depth: i_do_trsp must be set to 2
+z2_trsp=1000 ; # second depth: i_do_trsp must be set to 2
+
+# Solid freshwater transport through sections due to sea-ice drift
+export i_do_trsp_ice=1 ; # must have i_do_ice=1
+
+# Meridional heat/salt transport (advective)
+export i_do_mht=1
+
+# Transport by sigma class
+export i_do_sigt=1
+
+# Budget on pre-defined (FILE_DEF_BOXES) rectangular domains:
+export i_do_bb=0   ; # Budget and other stuffs on a given rectangular box!
+#             # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t)  (mean of 2D fields)
+
+# Vertical profiles on of box-averaged as a function of time...
+export i_do_box_TS_z=0 ; # do sigma vert. profiles on given boxes... # 1 => no figures, 2 => figures
+#                 # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t,z)
+
+# Deep Mixed volume in prescribed boxes:
+export i_do_dmv=0
+export MLD_CRIT="1000,725,500"
+
+# User-defined meridional or zonal cross sections (for temperature and salinity)
+# => TS_SECTION_FILE must be defined!
+export i_do_sect=1
+export TS_SECTION_FILE="${BARAKUDA_ROOT}/data/TS_sections.dat"
+
+
+# BETA / TESTING / NERDY (at your own risks...):
+#
+export i_do_ssx_box=0 ; # zoom on given boxes (+spatially-averaged values) for surface properties
+#                     # boxes defined into barakuda_orca.py ...
+
+# Some nerdy stuffs about the critical depth in prescribed boxes:
+export i_do_zcrit=0

+ 233 - 0
configs/config_ORCA1_L75_v36_BSC_gustafson.sh

@@ -0,0 +1,233 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for NEMO v3.6 of EC-Earth 3.2 on 75 levels
+#
+#        Machine: gustafson@BSC
+#
+#        L. Brodeau, 2017
+#
+#===========================================================
+
+export CONF=ORCA1.L75 ; # horizontal global ORCA configuration
+export NBL=75         ; # number of levels
+
+export HOST=GUSTAFSON ; # this has no importance at all, it will just become an "info" on the web-page!
+export MASTERMIND="BSC / Eleftheria" ; # same here, who's the person who designed/ran this simulation?
+
+export EXTRA_CONF="NEMO 3.6 + LIM 3 (EC-Earth 3.2)" ;   #  // same here ...
+
+# Path / directory structure in which to find NEMO output file (you can use
+# <ORCA> and <EXP> as substitute to your ORCA grid and experiment (EXP) name):
+export NEMO_OUT_STRCT="/esarchive/exp/nemo/<EXP>/<Y_INI_EC>0101/fc00/outputs"
+#                       /esarchive/exp/ecearth/a0go/original_files/19890101/fc0/outputs
+# Path to root directory where to save the diagnostics (diagnostics for this "CONF"):
+export DIAG_DIR="/scratch/Earth/${USER}/barakuda/${CONF}_ece32"
+
+# Path to directory containing some 2D and 3D climatologies on the relevant ORCA grid:
+export CONF_INI_DIR="/esnas/obs/barakuda/ORCA1.L75_barakuda"
+
+# Temporary file system (scratch) on which to perform the job you can use <JOB_ID> if scracth depends on JOB ID:
+export SCRATCH="/scratch/Earth/${USER}"
+
+export PYTHON_HOME="/home/Earth/lbrodeau/opt/Canopy/User" ; # HOME to python distribution with matplotlib and basemap !
+
+export DIR_NCVIEW_CMAP="${BARAKUDA_ROOT}/src/ncview_colormaps"
+
+# Is it an ec-earth experiment?
+export ece_exp=10; # 0 => not an EC-Earth experiment, it's a "pure" ocean-only NEMO experiment done from traditional NEMO setup
+#                  # 1 => it's an OCEAN-ONLY EC-Earth experiment done from a EC-Earth setup
+#                  # 2 => it's a  COUPLED  EC-Earth experiment
+#                  #      Both 1 and 2 imply that NEMO files are stored in something like
+#                  #       ${SOMEWHERE}/<EXP>/output/nemo/<YYY>
+#                  #       where YYY starts from '001' to
+#                  #      If you select '2', make sure 'cdo' is available and working!!!
+#                  # 10 => this experiment controled by AutoSubmit (so NEMO files are tared somerwhere?)
+#
+export Y_INI_EC=1958 ;    # initial year if ece_exp /= 0 !!!
+export TRES_IFS=XXX  ;    # spectral resolution for IFS, ex: T255 => TRES_IFS=255
+###--- end EC-Earth IFS relate section ---
+
+export ATMO_INFO="IFS T${TRES_IFS}" ; # Name of atmospheric model or forcing used (ex: COREv2, DFS5.2, IFS T255, ect...)
+
+# List of suffix of files that have been saved by NEMO and contain MONTHLY averages:
+export NEMO_SAVED_FILES="grid_T grid_U grid_V icemod"
+
+export TSTAMP="1m"   ; # output time-frequency stamp as in NEMO output files...
+
+# In case 3D fields have been saved on an annual mean basis rather than montly:
+export ANNUAL_3D="" ;   # leave blanck "" if 3D fields are in monthly files...
+export NEMO_SAVED_FILES_3D="" ; #     ''
+
+# How does the nemo files prefix looks like
+# Everything before "<year_related_info>_grid_<X>" or "<year_related_info>_icemod"
+# use <ORCA>, <EXP> and <TSTAMP>=>  Ex: export NEMO_FILE_PREFIX="<ORCA>-<EXP>_<TSTAMP>_"
+export NEMO_FILE_PREFIX="<EXP>_<TSTAMP>_"
+# => should get rid of TSTAMP actually...
+
+
+####### NEMO => what fields in what files ??? ############
+#       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#   => depends on the XIOS *.xml setup you used...
+#   => always specify a string for the NN_* variables
+#      USE "X" if the field is not present in your NEMO output
+#
+# State variables and others in grid_T files:
+export NN_SST="tos"
+export NN_SSS="sos"
+export NN_SSH="zos"
+export NN_T="thetao"
+export NN_S="so"
+export NN_MLD="mldr10_1"
+#
+# State variables and others in grid_U files:
+export NN_U="uo"
+export NN_TAUX="tauuo"
+export NN_U_EIV="0" ; # 0 => ignore
+# State variables and others in grid_V files:
+export NN_V="vo"
+export NN_TAUY="tauvo"
+export NN_V_EIV="0" ; # 0 => ignore
+#
+# Sea-ice fields:
+export FILE_ICE_SUFFIX="icemod" ; # in what file type extension to find ice fields
+export NN_ICEF="siconc" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="sivolu" ; # ice thickness or rather volume...
+export NN_ICEU="sivelu" ; # ice U-velocity
+export NN_ICEV="sivelv" ; # ice V-velocity
+#
+# Surface fluxes:
+export FILE_FLX_SUFFIX="grid_T" ; # in what file type extension to find surface fluxes
+####                           # => mind that $FILE_FLX_SUFFIX must be also in NEMO_SAVED_FILES (above)
+#### Note: in fields marked with *+/-* you can use a sum or substraction of variables (no space allowed!)
+####       ex: NN_EMP="evap_ao_cea+subl_ai_cea-precip"
+####           NN_QNET="qsr+qnsol"
+# ++ Surface freswater fluxes:
+export NN_FWF="X"        ; # name of net freshwater flux (E-P-R) in "FILE_FLX_SUFFIX" file...
+export NN_EMP="X"        ; # name of E-P in "FILE_FLX_SUFFIX" file...
+export NN_P="X"          ; # name of total precipitation (solid+liquid) in "FILE_FLX_SUFFIX" file...
+export NN_RNF="X"   ; # name of continental runoffs in "FILE_FLX_SUFFIX" file...
+export NN_CLV="X"        ; # calving from icebergs in "FILE_FLX_SUFFIX" file...
+export NN_E="X"          ; # name of total evaporation in "FILE_FLX_SUFFIX" file...
+# ++ Surface heat fluxes:
+export NN_QNET="qt_oce"       ; # name of total net surface heat flux in "FILE_FLX_SUFFIX" file...
+export NN_QSOL="qsr_oce"  ; # name of net surface solar flux in "FILE_FLX_SUFFIX" file...
+# ++ Wind-stress module:
+export NN_TAUM="X"        ; # name of surface wind stress module in "FILE_FLX_SUFFIX" file...
+export NN_WNDM="X"      ; # name of surface wind  speed module in "FILE_FLX_SUFFIX" file...
+#
+################################################################################################
+
+# Land-sea mask and basins files:
+export MM_FILE=${CONF_INI_DIR}/mesh_mask.nc4
+export BM_FILE=${BARAKUDA_ROOT}/data/basin_mask_ORCA1_ece3.2_2017.nc4
+
+# 3D monthly climatologies of potential temperature and salinity (can be those you used for the NEMO experiment):
+#export NM_TS_OBS="WOA_2009"
+#export F_T_OBS_3D_12=${CONF_INI_DIR}/thetao_1degx1deg-ORCA1.L75_WOA2009_monthly_LB_20160223.nc4
+#export F_S_OBS_3D_12=${CONF_INI_DIR}/so_1degx1deg-ORCA1.L75_WOA2009_monthly_LB_20160223.nc4
+#export F_SST_OBS_12=${CONF_INI_DIR}/tos_180x360-ORCA1_Reynolds_monthly_mean1982-2005.nc4
+#export NN_T_OBS="thetao"
+#export NN_S_OBS="so"
+#export NN_SST_OBS="tos"
+#
+export NM_TS_OBS="EN4.2.0 [1990-2010]"
+export F_T_OBS_3D_12=${CONF_INI_DIR}/thetao_EN.4.2.0_ORCA1L75_mclim_1990-2010.nc4
+export F_S_OBS_3D_12=${CONF_INI_DIR}/so_EN.4.2.0_ORCA1L75_mclim_1990-2010.nc4
+export F_SST_OBS_12=${CONF_INI_DIR}/thetao_EN.4.2.0_ORCA1L75_mclim_1990-2010.nc4
+export NN_T_OBS="thetao"
+export NN_S_OBS="so"
+export NN_SST_OBS="thetao"
+#
+export NM_IC_OBS="Hurrell et al 2008 [1980-1999]"
+export F_ICE_OBS_12=${CONF_INI_DIR}/ice_cover_180x360-ORCA1_Hurrell_monthly_mean1980-1999.nc4
+export NN_ICEF_OBS="ice_cover"
+
+
+# A text file where the cross sections (to compute transports) are defined :
+export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA1.dat"        ; # set i_do_trsp=1 !
+export TRANSPORT_SECTION_FILE_ICE="${BARAKUDA_ROOT}/data/transport_ice_ORCA1.dat"  ; # set i_do_trsp_ice=1 !
+
+# For transport by sigma-class:
+export DENSITY_SECTION_FILE="${BARAKUDA_ROOT}/data/dens_section_ORCA1.dat"
+
+# Files with the list of rectangular domains to "analyze" more closely:
+export FILE_DEF_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA1.txt"
+export FILE_DMV_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA1.txt"
+
+# In what format should figures be produced ('png' recommanded, but 'svg' supported!):
+export FIG_FORM="png"
+
+# About remote HOST to send/install HTML pages to:
+export ihttp=1                  ; # do we export on a remote http server (1) or keep on the local machine (0)
+export RHOST=bscct01.bsc.es ; # remote host to send diagnostic page to///
+export RUSER=${USER}             ; # username associated to remote host (for file export)
+export RWWWD=/bsc/www/htdocs/public/${USER}/BaraKuda ; # directory of the local or remote host to send the diagnostic page to
+
+
+#########################
+# Diags to be performed #
+#########################
+
+# Movies of SST and SSS compared to OBS:
+export i_do_movi=1
+export iffmpeg_x264=1 ; # is, by chance, ffmpeg with support for x264 encoding available on your stystem? => 1 !
+
+# Basic 3D and surface averages:
+export i_do_mean=1
+
+# IFS surface fluxes of heat and freshwater
+export i_do_ifs_flx=0 ; # only relevant when ece_exp=2...
+
+# AMOC:
+export i_do_amoc=1
+export LMOCLAT="20-23 30-33 40-43 45-48 50-53" ; # List of latitude bands to look in for max of AMOC
+
+# Sea-ice diags
+export i_do_ice=1  ; # Sea-ice diags
+
+# Transport of mass, heat and salt through specified sections (into TRANSPORT_SECTION_FILE):
+export i_do_trsp=1  ; # transport of mass, heat and salt through specified sections
+#              # i_do_trsp=2 => treat also different depths range!
+z1_trsp=100  ; # first  depth: i_do_trsp must be set to 2
+z2_trsp=1000 ; # second depth: i_do_trsp must be set to 2
+
+# Solid freshwater transport through sections due to sea-ice drift
+export i_do_trsp_ice=1 ; # must have i_do_ice=1
+
+# Meridional heat/salt transport (advective)
+export i_do_mht=1
+
+# Transport by sigma class
+export i_do_sigt=1
+
+# Budget on pre-defined (FILE_DEF_BOXES) rectangular domains:
+export i_do_bb=0   ; # Budget and other stuffs on a given rectangular box!
+#             # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t)  (mean of 2D fields)
+
+# Vertical profiles on of box-averaged as a function of time...
+export i_do_box_TS_z=0 ; # do sigma vert. profiles on given boxes... # 1 => no figures, 2 => figures
+#                 # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t,z)
+
+# Deep Mixed volume in prescribed boxes:
+export i_do_dmv=0
+export MLD_CRIT="1000,725,500"
+
+# User-defined meridional or zonal cross sections (for temperature and salinity)
+# => TS_SECTION_FILE must be defined!
+export i_do_sect=1
+export TS_SECTION_FILE="${BARAKUDA_ROOT}/data/TS_sections.dat"
+
+
+# BETA / TESTING / NERDY (at your own risks...):
+#
+export i_do_ssx_box=0 ; # zoom on given boxes (+spatially-averaged values) for surface properties
+#                     # boxes defined into barakuda_orca.py ...
+
+# Some nerdy stuffs about the critical depth in prescribed boxes:
+export i_do_zcrit=0

+ 226 - 0
configs/config_ORCA1_L75_valentina.sh

@@ -0,0 +1,226 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for NEMO v3.6 of EC-Earth 3.2 beta tunning on 75 levels
+#
+#        Machine: gustafson.bsc.es
+#
+#        L. Brodeau, 2017
+#
+#===========================================================
+
+export CONF=ORCA1.L75 ; # horizontal global ORCA configuration
+export NBL=75           ; # number of levels
+
+export HOST=`hostname`.bsc.es    ; # this has no importance at all, it will just become an "info" on the web-page!
+export MASTERMIND="BSC / Valentina" ; # same here, who's the person who designed/ran this simulation?
+
+export EXTRA_CONF="NEMO 3.6 + LIM 3 (EC-Earth 3???)" ;   #  // same here ...
+
+# Path / directory structure in which to find NEMO output file (you can use
+# <ORCA> and <EXP> as substitute to your ORCA grid and experiment (EXP) name):
+export NEMO_OUT_STRCT="/esarchive/exp/ecearth/<EXP>/original_files/<Y_INI_EC><M_INI_EC>01/fc0/outputs"
+
+# Path to root directory where to save the diagnostics (diagnostics for this "CONF"):
+export DIAG_DIR="/scratch/Earth/${USER}/barakuda/valentina"
+
+# Path to directory containing some 2D and 3D climatologies on the relevant ORCA grid:
+export CONF_INI_DIR="/esnas/obs/barakuda/ORCA1.L75_barakuda"
+
+# Temporary file system (scratch) on which to perform the job you can use <JOB_ID> if scracth depends on JOB ID:
+export SCRATCH="/scratch/Earth/${USER}"
+
+export PYTHON_HOME="/home/Earth/lbrodeau/opt/Canopy/User" ; # HOME to python distribution with matplotlib and basemap !
+
+export DIR_NCVIEW_CMAP="${BARAKUDA_ROOT}/src/ncview_colormaps"
+
+# Is it an ec-earth experiment?
+export ece_exp=10; # 0 => not an EC-Earth experiment, it's a "pure" ocean-only NEMO experiment done from traditional NEMO setup
+#                  # 1 => it's an OCEAN-ONLY EC-Earth experiment done from a EC-Earth setup
+#                  # 2 => it's a  COUPLED  EC-Earth experiment
+#                  #      Both 1 and 2 imply that NEMO files are stored in something like
+#                  #       ${SOMEWHERE}/<EXP>/output/nemo/<YYY>
+#                  #       where YYY starts from '001' to
+#                  #      If you select '2', make sure 'cdo' is available and working!!!
+#                  # 10 => this experiment controled by AutoSubmit (so NEMO files are tared somerwhere?)
+#
+export Y_INI_EC=1983 ;    # initial year if ece_exp /= 0 !!!
+export M_INI_EC="02" ;    # initial month, only needed if ece_exp >= 10 !!!
+export NCHNKS_Y=1    ;    # number of chunks per year if ece_exp >= 10 (only needed if NCHNKS_Y >= 2 !)
+export TRES_IFS=255  ;    # spectral resolution for IFS, ex: T255 => TRES_IFS=255
+###--- end EC-Earth IFS relate section ---
+
+export ATMO_INFO="IFS T${TRES_IFS}" ; # Name of atmospheric model or forcing used (ex: COREv2, DFS5.2, IFS T255, ect...)
+
+# List of suffix of files that have been saved by NEMO and contain MONTHLY averages:
+export NEMO_SAVED_FILES="grid_T grid_U grid_V icemod"
+
+export TSTAMP="1m"   ; # output time-frequency stamp as in NEMO output files...
+
+# In case 3D fields have been saved on an annual mean basis rather than montly:
+export ANNUAL_3D="" ;   # leave blanck "" if 3D fields are in monthly files...
+export NEMO_SAVED_FILES_3D="" ; #     ''
+# How does the nemo files prefix looks like
+# Everything before "<year_related_info>_grid_<X>" or "<year_related_info>_icemod"
+# use <ORCA>, <EXP> and <TSTAMP>=>  Ex: export NEMO_FILE_PREFIX="<ORCA>-<EXP>_<TSTAMP>_"
+export NEMO_FILE_PREFIX="<EXP>_<TSTAMP>_"
+# => should get rid of TSTAMP actually...
+
+
+####### NEMO => what fields in what files ??? ############
+#       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#   => depends on the XIOS *.xml setup you used...
+#   => always specify a string for the NN_* variables
+#      USE "X" if the field is not present in your NEMO output
+#
+# State variables and others in grid_T files:
+export NN_SST="tos"
+export NN_SSS="sos"
+export NN_SSH="zos"
+export NN_T="thetao"
+export NN_S="so"
+export NN_MLD="mldr10_1"
+#
+# State variables and others in grid_U files:
+export NN_U="uo"
+export NN_TAUX="tauuo"
+export NN_U_EIV="0" ; # 0 => ignore
+# State variables and others in grid_V files:
+export NN_V="vo"
+export NN_TAUY="tauvo"
+export NN_V_EIV="0" ; # 0 => ignore
+#
+# Sea-ice fields:
+export FILE_ICE_SUFFIX="icemod" ; # in what file type extension to find ice fields
+export NN_ICEF="siconc" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="sivolu" ; # ice thickness or rather volume...
+export NN_ICEU="sivelu" ; # ice U-velocity
+export NN_ICEV="sivelv" ; # ice V-velocity
+#
+# Surface fluxes:
+export FILE_FLX_SUFFIX="grid_T" ; # in what file type extension to find surface fluxes
+####                           # => mind that $FILE_FLX_SUFFIX must be also in NEMO_SAVED_FILES (above)
+#### Note: in fields marked with *+/-* you can use a sum or substraction of variables (no space allowed!)
+####       ex: NN_EMP="evap_ao_cea+subl_ai_cea-precip"
+####           NN_QNET="qsr+qnsol"
+# ++ Surface freswater fluxes:
+export NN_FWF="wfo"        ; # name of net freshwater flux (E-P-R) in "FILE_FLX_SUFFIX" file...
+export NN_EMP="X"        ; # name of E-P in "FILE_FLX_SUFFIX" file...
+export NN_P="X"          ; # name of total precipitation (solid+liquid) in "FILE_FLX_SUFFIX" file...
+export NN_RNF="friver"   ; # name of continental runoffs in "FILE_FLX_SUFFIX" file...
+export NN_CLV="X"        ; # calving from icebergs in "FILE_FLX_SUFFIX" file...
+export NN_E="X"          ; # name of total evaporation in "FILE_FLX_SUFFIX" file...
+# ++ Surface heat fluxes:
+export NN_QNET="nshfls+rsntds" ; # name of total net surface heat flux in "FILE_FLX_SUFFIX" file...
+export NN_QSOL="rsntds"  ; # name of net surface solar flux in "FILE_FLX_SUFFIX" file...
+# ++ Wind-stress module:
+export NN_TAUM="X"        ; # name of surface wind stress module in "FILE_FLX_SUFFIX" file...
+export NN_WNDM="X"      ; # name of surface wind  speed module in "FILE_FLX_SUFFIX" file...
+#
+################################################################################################
+
+# Land-sea mask and basins files:
+export MM_FILE=${CONF_INI_DIR}/mesh_mask.nc4
+export BM_FILE=${BARAKUDA_ROOT}/data/basin_mask_ORCA1_ece3.2_2017.nc4
+
+# 3D monthly climatologies of potential temperature and salinity (can be those you used for the NEMO experiment):
+export NM_TS_OBS="EN4.2.0 [1990-2010]"
+export F_T_OBS_3D_12=${CONF_INI_DIR}/thetao_EN.4.2.0_ORCA1L75_mclim_1990-2010.nc4
+export F_S_OBS_3D_12=${CONF_INI_DIR}/so_EN.4.2.0_ORCA1L75_mclim_1990-2010.nc4
+export F_SST_OBS_12=${CONF_INI_DIR}/thetao_EN.4.2.0_ORCA1L75_mclim_1990-2010.nc4
+export NN_T_OBS="thetao"
+export NN_S_OBS="so"
+export NN_SST_OBS="thetao"
+#
+export NM_IC_OBS="Hurrell et al 2008 [1980-1999]"
+export F_ICE_OBS_12=${CONF_INI_DIR}/ice_cover_180x360-ORCA1_Hurrell_monthly_mean1980-1999.nc4
+export NN_ICEF_OBS="ice_cover"
+
+
+# A text file where the cross sections (to compute transports) are defined :
+export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_ORCA1.dat"        ; # set i_do_trsp=1 !
+export TRANSPORT_SECTION_FILE_ICE="${BARAKUDA_ROOT}/data/transport_ice_ORCA1.dat"  ; # set i_do_trsp_ice=1 !
+
+# For transport by sigma-class:
+export DENSITY_SECTION_FILE="${BARAKUDA_ROOT}/data/dens_section_ORCA1.dat"
+
+# Files with the list of rectangular domains to "analyze" more closely:
+export FILE_DEF_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA1.txt"
+export FILE_DMV_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_ORCA1.txt"
+
+# In what format should figures be produced ('png' recommanded, but 'svg' supported!):
+export FIG_FORM="png"
+
+# About remote HOST to send/install HTML pages to:
+export ihttp=1                  ; # do we export on a remote http server (1) or keep on the local machine (0)
+export RHOST=bscct01.bsc.es ; # remote host to send diagnostic page to///
+export RUSER=${USER}             ; # username associated to remote host (for file export)
+export RWWWD=/bsc/www/htdocs/public/${USER}/BaraKuda ; # directory of the local or remote host to send the diagnostic page to
+
+
+#########################
+# Diags to be performed #
+#########################
+
+# Movies of SST and SSS compared to OBS:
+export i_do_movi=1
+export iffmpeg_x264=1 ; # is, by chance, ffmpeg with support for x264 encoding available on your stystem? => 1 !
+
+# Basic 3D and surface averages:
+export i_do_mean=1
+
+# IFS surface fluxes of heat and freshwater
+export i_do_ifs_flx=0 ; # only relevant when ece_exp=2...
+
+# AMOC:
+export i_do_amoc=1
+export LMOCLAT="20-23 30-33 40-43 45-48 50-53" ; # List of latitude bands to look in for max of AMOC
+
+# Sea-ice diags
+export i_do_ice=1  ; # Sea-ice diags
+
+# Transport of mass, heat and salt through specified sections (into TRANSPORT_SECTION_FILE):
+export i_do_trsp=1  ; # transport of mass, heat and salt through specified sections
+#              # i_do_trsp=2 => treat also different depths range!
+z1_trsp=100  ; # first  depth: i_do_trsp must be set to 2
+z2_trsp=1000 ; # second depth: i_do_trsp must be set to 2
+
+# Solid freshwater transport through sections due to sea-ice drift
+export i_do_trsp_ice=1 ; # must have i_do_ice=1
+
+# Meridional heat/salt transport (advective)
+export i_do_mht=1
+
+# Transport by sigma class
+export i_do_sigt=1
+
+# Budget on pre-defined (FILE_DEF_BOXES) rectangular domains:
+export i_do_bb=0   ; # Budget and other stuffs on a given rectangular box!
+#             # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t)  (mean of 2D fields)
+
+# Vertical profiles on of box-averaged as a function of time...
+export i_do_box_TS_z=0 ; # do sigma vert. profiles on given boxes... # 1 => no figures, 2 => figures
+#                 # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t,z)
+
+# Deep Mixed volume in prescribed boxes:
+export i_do_dmv=0
+export MLD_CRIT="1000,725,500"
+
+# User-defined meridional or zonal cross sections (for temperature and salinity)
+# => TS_SECTION_FILE must be defined!
+export i_do_sect=1
+export TS_SECTION_FILE="${BARAKUDA_ROOT}/data/TS_sections.dat"
+
+
+# BETA / TESTING / NERDY (at your own risks...):
+#
+export i_do_ssx_box=0 ; # zoom on given boxes (+spatially-averaged values) for surface properties
+#                     # boxes defined into barakuda_orca.py ...
+
+# Some nerdy stuffs about the critical depth in prescribed boxes:
+export i_do_zcrit=0

+ 223 - 0
configs/config_ORCA2_L31_ece32_marenostrum.sh

@@ -0,0 +1,223 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for NEMO-ORCA2 v3.6 of EC-Earth 3.2 beta tunning on 31 levels
+#
+#            Machine: MareNostrum@BSC
+#
+#        L. Brodeau, January 2017
+#
+#===========================================================
+
+export HCONF=ORCA2
+export CONF=${HCONF}.L31 ; # horizontal global ORCA configuration
+export NBL=31         ; # number of levels
+
+export HOST=MARENOSTRUM ; # this has no importance at all, it will just become an "info" on the web-page!
+export EXTRA_CONF="LIM3, IFS T159, NEMO 3.6 (EC-Earth 3.2)" ;   #  // same here ...
+
+# File system / path on which most netcdf data will be read:
+export STORE_DIR="/gpfs/scratch/bsc32/bsc32325"
+
+# Path to directory containing some 2D and 3D climatologies on the relevant ORCA grid:
+export CONF_INI_DIR="/gpfs/projects/bsc32/bsc32325/${HCONF}/${HCONF}-I"
+
+# In what directory of the local machine to save the diagnostics:
+export DIAG_DIR="${STORE_DIR}/barakuda/${CONF}_ece32"
+
+# --- only for problematic hosts ----
+module add NCO/4.2.3    
+module add PYTHON/2.7.3
+# -----------------------------------
+
+export PYTHON_HOME="/apps/PYTHON/2.7.3" ; # HOME to python distribution with matplotlib and basemap !
+
+# Is it an ec-earth run?
+export ece_run=2 ; # 0 => not an EC-Earth run, it's a "pure" ocean-only NEMO run done from traditional NEMO setup
+#                  # 1 => it's an OCEAN-ONLY EC-Earth run done from a EC-Earth setup
+#                  # 2 => it's a  COUPLED  EC-Earth run
+#                  #      Both 1 and 2 imply that NEMO files are stored in something like
+#                  #       ${STORE_DIR}/<RUN>/output/nemo/<YYY>
+#                  #       where YYY starts from '001' to
+#                  #   If you select '2', make sure 'cdo' is available and working!!!
+#
+export Y_INI_EC=1990 ;    # initial year if ec-earth run...
+
+# List of suffixed of files that have been saved by NEMO and that are needed for the diags:
+export NEMO_SAVED_FILES="grid_T grid_U grid_V icemod SBC"
+
+# Directory structure in which to find NEMO output file (use <ORCA> and <RUN>):
+export NEMO_OUT_STRCT="${STORE_DIR}/run_ece/<RUN>/output/nemo"
+
+export TSTAMP="1m"   ; # output time-frequency stamp as in NEMO output files...
+
+# How does the nemo files prefix looks like
+# Everything before "<year_related_info>_grid_<X>" or "<year_related_info>_icemod"
+# use <ORCA>, <RUN> and <TSTAMP>=>  Ex: export NEMO_FILE_PREFIX="<ORCA>-<RUN>_<TSTAMP>_"
+export NEMO_FILE_PREFIX="<RUN>_<TSTAMP>_"
+# => should get rid of TSTAMP actually...
+
+# Temporary file system (scratch) on which to perform the job you can use <JOB_ID> if scracth depends on JOB ID:
+export SCRATCH="/scratch/tmp"
+
+
+####### NEMO => what fields in what files ??? ############
+#       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#   => depends on the XIOS *.xml setup you used...
+#   => always specify a string for the NN_* variables
+#      even when missing from your files (ex: NN_MLD="xx")
+#
+# State variables and others in grid_T files:
+export NN_SST="sosstsst"
+export NN_SSS="sosaline"
+export NN_SSH="sossheig"
+export NN_T="votemper"
+export NN_S="vosaline"
+export NN_MLD="mldr10_1"
+#
+# State variables and others in grid_U files:
+export NN_U="vozocrtx"
+export NN_TAUX="sozotaux"
+export NN_U_EIV="0" ; # 0 => ignore
+# State variables and others in grid_V files:
+export NN_V="vomecrty"
+export NN_TAUY="sometauy"
+export NN_V_EIV="0" ; # 0 => ignore
+#
+# Sea-ice fields:
+export FILE_ICE_SUFFIX="icemod" ; # in what file type extension to find ice fields
+export NN_ICEF="siconc" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="sivolu" ; # ice thickness or rather volume...
+#
+# Surface fluxes:
+export FILE_FLX_SUFFIX="SBC" ; # in what file type extension to find surface fluxes
+export NN_FWF="empmr"        ; # name of net freshwater flux (E-P-R) in "FILE_FLX_SUFFIX" file...
+export NN_EMP="emp_oce"      ; # name of E-P in "FILE_FLX_SUFFIX" file...
+export NN_P="precip"         ; # name of total precipitation (solid+liquid) in "FILE_FLX_SUFFIX" file...
+export NN_RNF="runoffs"      ; # name of continental runoffs in "FILE_FLX_SUFFIX" file...
+export NN_CLV="calving"      ; # calving from icebergs in "FILE_FLX_SUFFIX" file...
+export NN_E="evapo"          ; # name of total evaporation in "FILE_FLX_SUFFIX" file...
+export NN_QNET="qt"          ; # name of total net surface heat flux in "FILE_FLX_SUFFIX" file...
+export NN_QSOL="qsr"         ; # name of net surface solar flux in "FILE_FLX_SUFFIX" file...
+#
+################################################################################################
+
+# Land-sea mask and basins files:
+export MM_FILE=/gpfs/projects/bsc32/bsc32325/${HCONF}/mesh_mask.nc4
+export BM_FILE=${CONF_INI_DIR}/subbasins_laurent.nc
+
+# 3D monthly climatologies of potential temperature and salinity (can be those you used for the NEMO run):
+export F_T_CLIM_3D_12=${CONF_INI_DIR}/data_1m_potential_temperature_nomask_${HCONF}.nc
+export F_S_CLIM_3D_12=${CONF_INI_DIR}/data_1m_salinity_nomask_${HCONF}.nc
+export SST_CLIM_12=${CONF_INI_DIR}/sst_data_${HCONF}.nc
+export NN_T_CLIM="votemper"
+export NN_S_CLIM="vosaline"
+export NN_SST_CLIM="sst"
+
+export ICE_CLIM_12=${CONF_INI_DIR}/ice_cover_180x360-${HCONF}_Hurrell_monthly_mean1980-1999.nc4
+export NN_ICEF_CLIM="ice_cover"
+
+
+# A text file where the vertical hydraugraphical sections of interest are defined :
+export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_${HCONF}_all.dat"
+
+# For transport by sigma-class:
+export DENSITY_SECTION_FILE="${BARAKUDA_ROOT}/data/dens_section_${HCONF}.dat"
+
+# Files with the list of rectangular domains to "analyze" more closely:
+export FILE_DEF_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_${HCONF}.txt"
+export FILE_DMV_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_${HCONF}.txt"
+
+# In what format should figures be produced ('png' recommanded, 'svg' works):
+export FIG_FORM="png"
+
+# About remote HOST to send/install HTML pages to:
+export ihttp=0                  ; # do we export on a remote http server (1) or keep on the local machine (0)
+export RHOST=whitehouse.gov.org ; # remote host to send diagnostic page to///
+export RUSER=donald             ; # username associated to remote host (for file export)
+export RWWWD=/data/www/barakuda/ec-earth_3.2b ; # directory of the local or remote host to send the diagnostic page to
+
+
+
+#########################
+# Diags to be performed #
+#########################
+
+# Movies of SST and SSS compared to OBS:
+export i_do_movi=1
+
+# Basic 3D and surface averages:
+export i_do_mean=1
+
+# IFS surface fluxes of heat and freshwater
+export i_do_ifs_flx=1 ; # only relevant when ece_run=2...
+
+# AMOC:
+export i_do_amoc=1
+export LMOCLAT="20-23 30-33 40-43 45-48 50-53" ; # List of latitude bands to look in for max of AMOC
+
+# Transport of mass, heat and salt through specified sections (into TRANSPORT_SECTION_FILE):
+export i_do_trsp=1  ; # transport of mass, heat and salt through specified sections
+#              # i_do_trsp=2 => treat also different depths range!
+z1_trsp=100  ; # first  depth: i_do_trsp must be set to 2
+z2_trsp=1000 ; # second depth: i_do_trsp must be set to 2
+
+# Meridional heat/salt transport (advective)
+export i_do_mht=1
+
+# Transport by sigma class
+export i_do_sigt=1
+
+# Sea-ice diags
+export i_do_ice=1  ; # Sea-ice diags
+
+# Budget on pre-defined (FILE_DEF_BOXES) rectangular domains:
+export i_do_bb=1   ; # Budget and other stuffs on a given rectangular box!
+#             # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t)  (mean of 2D fields)
+
+# Vertical profiles on of box-averaged as a function of time...
+export i_do_box_TS_z=1 ; # do sigma vert. profiles on given boxes... # 1 => no figures, 2 => figures
+#                 # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t,z)
+
+# Deep Mixed volume in prescribed boxes:
+export i_do_dmv=1
+export MLD_CRIT="1000,725,500"
+
+# User-defined meridional or zonal cross sections (for temperature and salinity)
+# => TS_SECTION_FILE must be defined!
+export i_do_sect=1
+export TS_SECTION_FILE="${BARAKUDA_ROOT}/data/TS_sections.dat"
+
+
+
+# BETA / TESTING / NERDY (at your own risks...):
+#
+export i_do_ssx_box=0 ; # zoom on given boxes (+spatially-averaged values) for surface properties
+#                     # boxes defined into barakuda_orca.py ...
+
+# Some nerdy stuffs about the critical depth in prescribed boxes:
+export i_do_zcrit=0
+
+# Fresh-water transport associated to sea-ice transport
+#  => must compile cdficeflux.x but depends on more recent CDFTOOLS module...
+export i_do_icet=0 ; # treat sea-ice volume transport!
+export TRANSPORT_ICE_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_${HCONF}_ARCTIC.dat"
+
+export i_do_amo=0 ;  # buit a SST time serie usable to build Atlantic Multidecadal Oscilation index
+
+
+
+
+# Place for potential specific host-related survival tricks:
+
+#========================== Marenostrum @ BSC =========================================================
+### Shouldn't be needed elsewhere than MareNostrum, where it's a hello to have CDO working...
+## => Only if you specified ece_run=2 and i_do_ifs_flx
+export MOD_CDO="gcc/4.7.2 intel/13.0.1 openmpi/1.8.1 NETCDF/4.1.3 HDF5/1.8.10 UDUNITS/2.1.24 CDO/1.7.0"
+#=======================================================================================================
+

+ 211 - 0
configs/config_ORCA2_L31_v36_triolith.sh

@@ -0,0 +1,211 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for NEMO v3.6 ORCA2 on 31 levels
+#
+#            HPC: triolith
+#
+#        L. Brodeau, 2015
+#
+#===========================================================
+
+export CONF=ORCA2 ; # horizontal global configuration
+export NBL=31     ; # number of levels
+
+# File system where NEMO config and output files are stored:
+export STORE_DIR="/proj/bolinc/users/x_laubr"
+
+
+# Is it an ec-earth run?
+export ece_run=0 ; # means that NEMO files in something like ${STORE_DIR}/<RUN>/output/nemo/<YYY>
+#                  # where YYY starts from '001' to
+export Y_INI_EC=1990 ;    # initial year if ec-earth run...
+
+# List of suffixed of files that have been saved by NEMO and that are needed for the diags:
+export NEMO_SAVED_FILES="grid_T grid_U grid_V icemod SBC"
+
+
+# Directory structure in which to find NEMO output file (use <ORCA> and <RUN>):
+export NEMO_OUT_STRCT="${STORE_DIR}/<ORCA>/<ORCA>-<RUN>-S"
+
+export TSTAMP="1m"   ; # output time-frequency stamp as in NEMO output files...
+
+# How does the nemo files prefix looks like
+# Everything before "<year_related_info>_grid_<X>" or "<year_related_info>_icemod"
+# use <ORCA>, <RUN> and <TSTAMP>=>  Ex: export NEMO_FILE_PREFIX="<ORCA>-<RUN>_<TSTAMP>_"
+export NEMO_FILE_PREFIX="<ORCA>-<RUN>_<TSTAMP>_"
+# => should get rid of TSTAMP actually...
+
+# Temporary file system (scratch) on which to perform the job you can use <JOB_ID> if scracth depends on JOB ID:
+export SCRATCH="/scratch/local/<JOB_ID>"
+
+export PYTHON_HOME=${HOME}/opt/Canopy_64bit/User
+
+# If variables names in NEMO files are not the default...
+export NN_SST="tos"
+export NN_SSS="sos"
+export NN_SSH="zos"
+export NN_T="thetao"
+export NN_S="so"
+export NN_MLD="mldr10_1"
+export NN_U="uo"
+export NN_V="vo"
+#export NN_U_EIV="vozoeivu"
+#export NN_V_EIV="vomeeivv"
+export NN_U_EIV="0" ; # ignore
+export NN_V_EIV="0" ; # ignore
+export NN_TAUX="tauuo"
+export NN_TAUY="tauvo"
+
+export FILE_ICE_SUFFIX="icemod" ; # in what file to find ice fraction and volume?
+export NN_ICEF="siconc" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="sivolu" ; # ice thickness or rather volume...
+
+export FILE_FLX_SUFFIX="SBC" ; # in what file to find surface fluxes ?
+export NN_FWF="wfo"       ; # name of net freshwater flux (E-P-R) in "FILE_FLX_SUFFIX" file...
+export NN_EMP="emp_oce"   ; # name of E-P in "FILE_FLX_SUFFIX" file...
+export NN_P="precip"   ; # name of P in "FILE_FLX_SUFFIX" file...
+export NN_RNF="XXX"          ; # name of continental runoffs in "FILE_FLX_SUFFIX" file...
+export NN_CLV="XXX"  ; # calving from icebergs in "FILE_FLX_SUFFIX" file...
+export NN_E="XXX"           ; # evaporation in "FILE_FLX_SUFFIX" file...
+
+
+export L_CONV2NC3=false ; # Set to true if your NEMO output is in Netcdf4 and your NCO does not support netcdf4!
+
+export L_RENAME=false ; # set to true if your ORCA output has old name convention (ex: votemper instead of thetao)
+
+
+export EXTRA_CONF="NEMO v3.6 ${CONF} (L${NBL}) - LIM3 / ocean-only experiment"
+
+# Land-sea mask and basins files:
+export MM_FILE="/proj/bolinc/users/x_laubr/${CONF}/mesh_mask_${CONF}_20151014.nc"
+export BM_FILE="/proj/bolinc/users/x_laubr/${CONF}/basin_mask_${CONF}.nc"
+
+# 3D monthly climatologies of potential temperature and salinity (can be those you used for the NEMO run):
+export F_T_CLIM_3D_12=${STORE_DIR}/${CONF}/${CONF}-I/data_1m_potential_temperature_nomask_${CONF}.nc
+export F_S_CLIM_3D_12=${STORE_DIR}/${CONF}/${CONF}-I/data_1m_salinity_nomask_${CONF}.nc
+export SST_CLIM_12=${STORE_DIR}/${CONF}/${CONF}-I/sst_data_${CONF}.nc
+export NN_T_CLIM="votemper"
+export NN_S_CLIM="vosaline"
+export NN_SST_CLIM="sst"
+
+export ICE_CLIM_12="${STORE_DIR}/${CONF}/${CONF}-I/ice_cover_180x360-${CONF}_Hurrell_monthly_mean1980-1999.nc4"
+export NN_ICEF_CLIM="ice_cover"
+
+
+# A text file where the vertical hydraugraphical sections of interest are defined :
+#export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_${CONF}_light.dat"
+export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_${CONF}_all.dat"
+
+# For transport by sigma-class:
+export DENSITY_SECTION_FILE="${BARAKUDA_ROOT}/data/dens_section_${CONF}.dat"
+
+
+# In what directory of the local machine to save the diagnostics:
+export DIAG_DIR="/proj/bolinc/users/x_laubr/tmp/barakuda/${CONF}_v36"
+
+
+# Files with the list of rectangular boxes to look at more closely:
+export FILE_DEF_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_${CONF}.txt"
+
+
+
+# About remote HOST to install HTML pages to:
+ihttp=1 ; # do we export on a remote http server (1) or keep on the local machine (0)
+RHOST=misu228.misu.su.se ; # remote host to send diagnostic page to///
+RUSER=laurent ; # username associated to remote host (for file export)
+RWWWD=/data/www/barakuda/${CONF} ; # directory of the local or remote host to send the diagnostic page to
+
+
+
+
+#########################
+# Diags to be performed #
+#########################
+
+# In what format should figures be produced:
+export FIG_FORM="png"
+
+
+
+# Basic 3D and surface averages:
+i_do_mean=1
+
+# FreshWater fluxes at the surface spatially averaged over the ocean, E-P-R, E-P, R, P, ...
+#i_do_fwf=1
+
+# AMOC:
+i_do_amoc=1
+export LMOCLAT="20-23 30-33 40-43 45-48 50-53" ; # List of latitude bands to look in for max of AMOC
+
+
+# Transport of mass, heat and salt through specified sections (into TRANSPORT_SECTION_FILE):
+i_do_trsp=2  ; # transport of mass, heat and salt through specified sections
+#              # i_do_trsp=2 => treat also different depths range!
+z1_trsp=100  ; # first  depth: i_do_trsp must be set to 2
+z2_trsp=1000 ; # second depth: i_do_trsp must be set to 2
+
+
+# meridional heat/salt transport (advective)
+i_do_mht=1
+
+# Transport by sigma class
+i_do_sigt=1
+
+# sea-ice diags
+i_do_ice=1  ; # Sea-ice diags
+
+
+i_do_bb=1   ; # Budget and other stuffs on a given rectangular box!
+#             # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t)  (mean of 2D fields)
+
+
+i_do_ssx_box=0 ; # zoom on given boxes (+spatially-averaged values) for surface properties
+#                # boxes defined into barakuda_orca.py ...
+
+
+# Vertical profiles on of box-averaged as a function of time...
+i_do_box_TS_z=1 ; # do sigma vert. profiles on given boxes... # 1 => no figures, 2 => figures
+#                 # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t,z)
+
+#
+# Deep Mixed volume in prescribed boxes:
+i_do_dmv=0
+export MLD_CRIT="1000,725,500"
+
+
+# Some nerdy stuffs about the critical depth in prescribed boxes:
+i_do_zcrit=0
+
+
+
+
+
+
+# BETA / TESTING:
+
+# Fresh-water transport associated to sea-ice transport
+#  => must compile cdficeflux.x but depends on more recent CDFTOOLS module...
+i_do_icet=0 ; # treat sea-ice volume transport!
+export TRANSPORT_ICE_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_${CONF}_ARCTIC.dat"
+
+
+
+
+i_do_flx=0  ; # surface fluxes diags
+
+
+
+
+i_do_amo=0 ;  # buit a SST time serie usable to build Atlantic Multidecadal Oscilation index
+
+
+i_do_sect=0 ; # do sigma vert. profiles on given boxes...
+VSECT_NM=( "Indian_77p5_E" "Atlantic_21p5_W" )
+VSECT_JI=(      "5,5"          "266,266"     ) ; # X range in C convention
+VSECT_JJ=(    "25,170"          "7,291"      ) ; # Y range in C convention

+ 215 - 0
configs/config_eORCA1_L75_v36_voima.sh

@@ -0,0 +1,215 @@
+#!/bin/bash
+
+#==========================================================
+#
+#         Configuration file for
+#
+# OCEAN MONITORING for NEMO v3.6 eORCA1 on 75 levels
+#
+#            HPC: voima.fmi.fi
+#
+#        L. Brodeau, 2015
+#
+#===========================================================
+
+l_clim_diag=true ; # should we try to perform climatology-related diagnostics? (clim must be built!)
+
+export CONF=eORCA1.L75 ; # horizontal global configuration
+export NBL=75     ; # number of levels
+
+# Root directory where NEMO output files are stored:
+export STORE_DIR="/lustre/tmp/$USER"
+
+# List of suffixed of files that have been saved by NEMO:
+export NEMO_SAVED_FILES="grid_T grid_U grid_V icemod"
+
+
+# Directory structure in which to find NEMO output file (use <ORCA> and <RUN>):
+export NEMO_OUT_STRCT="${STORE_DIR}/<ORCA>/<ORCA>-<RUN>-S"
+
+export TSTAMP="1m"   ; # output time-frequency stamp as in NEMO output files...
+
+# How does the nemo files prefix looks like
+# Everything before "<year_related_info>_grid_<X>" or "<year_related_info>_icemod"
+# use <ORCA>, <RUN> and <TSTAMP>=>  Ex: export NEMO_FILE_PREFIX="<ORCA>-<RUN>_<TSTAMP>_"
+export NEMO_FILE_PREFIX="<ORCA>-<RUN>_<TSTAMP>_"
+# => should get rid of TSTAMP actually...
+
+# Temporary file system (scratch) on which to perform the job you can use <JOB_ID> if scracth depends on JOB ID:
+export SCRATCH="/lustre/tmp/$USER/tmp/${PBS_JOBID}"
+
+# Python installation directory where bin lib include reside
+export PYTHON_HOME=/opt/Python/2.7
+
+# NETCDF binaries such as nccopy
+export NCDF_BIN=/opt/cray/netcdf/4.3.0/bin
+
+# If variables names in NEMO files are not the default...
+export NN_SST="tos"
+export NN_SSS="sos"
+export NN_SSH="zos"
+export NN_T="thetao"
+export NN_S="so"
+export NN_MLD="mldr10_1"
+export NN_U="uo"
+export NN_V="vo"
+#export NN_U_EIV="vozoeivu"
+#export NN_V_EIV="vomeeivv"
+export NN_U_EIV="0" ; # ignore
+export NN_V_EIV="0" ; # ignore
+export NN_TAUX="tauuo"
+export NN_TAUY="tauvo"
+
+export FILE_ICE_SUFFIX="icemod" ; # in what file to find ice fraction NN_ICEF? => "icemod" or "grid_T"
+export NN_ICEF="siconc" ; # name of ice fraction in "FILE_ICE_SUFFIX" file...
+export NN_ICET="sivolu" ; # ice thickness or rather volume...
+
+export FILE_FLX_SUFFIX="SBC" ; # in what file to find surface fluxes ?
+export NN_FWF="wfo"         ; # name of net freshwater flux (E-P-R) in "FILE_FLX_SUFFIX" file...
+#export NN_FWF="empmr"        ; # name of net freshwater flux (E-P-R) in "FILE_FLX_SUFFIX" file...
+export NN_EMP="emp_oce"     ; # name of E-P in "FILE_FLX_SUFFIX" file...
+#export NN_EMP="emp"          ; # name of E-P in "FILE_FLX_SUFFIX" file...
+export NN_P="precip"         ; # name of P in "FILE_FLX_SUFFIX" file...
+export NN_RNF="runoffs"      ; # name of continental runoffs in "FILE_FLX_SUFFIX" file...
+export NN_CLV="calving_cea"  ; # calving from icebergs in "FILE_FLX_SUFFIX" file...
+export NN_E="evap"           ; # evaporation in "FILE_FLX_SUFFIX" file...
+
+
+export L_CONV2NC3=false ; # Set to true if your NEMO output is in Netcdf4 and your NCO does not support netcdf4!
+
+export L_RENAME=false ; # set to true if your ORCA output has old name convention (ex: votemper instead of thetao)
+
+
+export EXTRA_CONF="NEMO v3.6 ${CONF} (L${NBL}) - LIM3 / ocean-only experiment"
+
+# Land-sea mask and basins files:
+export MM_FILE="/lustre/tmp/uotilap/SHACONEMO/INPUT/eORCA1L75/mesh_mask_eORCA1L75.nc"
+export BM_FILE="/lustre/tmp/uotilap/SHACONEMO/INPUT/eORCA1L75/basin_mask_eORCA1L75.nc"
+
+# 3D monthly climatologies of potential temperature and salinity (can be those you used for the NEMO run):
+export CDATDIR=/stornext/field/users/${USER}
+export F_T_CLIM_3D_12=${CDATDIR}/tiede/PHC/PHC3.0.eORCA1.L75.nc
+export F_S_CLIM_3D_12=${CDATDIR}/tiede/PHC/PHC3.0.eORCA1.L75.nc
+export SST_CLIM_12=${CDATDIR}/tiede/PHC/PHC3.0.eORCA1.L75.nc
+export NN_T_CLIM="T"
+export NN_S_CLIM="S"
+export NN_SST_CLIM="sst"
+
+export ICE_CLIM_12=${CDATDIR}/sidads.colorado.edu/pub/DATASETS/NOAA/G02202_v2/seaice_conc_ymonmean_1994-2013.eORCA1.nc
+export NN_ICEF_CLIM="seaice_conc_monthly_cdr"
+
+
+# A text file where the vertical hydraugraphical sections of interest are defined :
+#export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_${CONF}_light.dat"
+export TRANSPORT_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_eORCA1.dat"
+
+# For transport by sigma-class:
+export DENSITY_SECTION_FILE="${BARAKUDA_ROOT}/data/dens_section_eORCA1.dat"
+
+
+# In what directory of the local machine to save the diagnostics:
+export DIAG_DIR="/lustre/tmp/${USER}/barakuda/${CONF}"
+
+
+# Files with the list of rectangular boxes to look at more closely:
+export FILE_DEF_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_eORCA1.txt"
+export FILE_DMV_BOXES="${BARAKUDA_ROOT}/data/def_boxes_convection_eORCA1.txt"
+
+
+
+# About remote HOST to install HTML pages to:
+ihttp=0 ; # do we export on a remote http server (1) or keep on the local machine (0)
+RHOST=misu228.misu.su.se ; # remote host to send diagnostic page to///
+RUSER=laurent ; # username associated to remote host (for file export)
+RWWWD=/data/www/barakuda/${CONF} ; # directory of the local or remote host to send the diagnostic page to
+
+
+
+
+#########################
+# Diags to be performed #
+#########################
+
+# In what format should figures be produced:
+export FIG_FORM="png"
+
+
+
+# Basic 3D and surface averages:
+i_do_mean=1
+
+# FreshWater fluxes at the surface spatially averaged over the ocean, E-P-R, E-P, R, P, ...
+#i_do_fwf=1
+
+# AMOC:
+i_do_amoc=1
+export LMOCLAT="20-23 30-33 40-43 45-48 50-53" ; # List of latitude bands to look in for max of AMOC
+
+
+# Transport of mass, heat and salt through specified sections (into TRANSPORT_SECTION_FILE):
+i_do_trsp=2  ; # transport of mass, heat and salt through specified sections
+#              # i_do_trsp=2 => treat also different depths range!
+z1_trsp=100  ; # first  depth: i_do_trsp must be set to 2
+z2_trsp=1000 ; # second depth: i_do_trsp must be set to 2
+
+
+# meridional heat/salt transport (advective)
+i_do_mht=1
+
+# Transport by sigma class
+i_do_sigt=1
+
+# sea-ice diags
+i_do_ice=1  ; # Sea-ice diags
+
+
+i_do_bb=1   ; # Budget and other stuffs on a given rectangular box!
+#             # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t)  (mean of 2D fields)
+
+
+i_do_ssx_box=0 ; # zoom on given boxes (+spatially-averaged values) for surface properties
+#                # boxes defined into barakuda_orca.py ...
+
+
+# Vertical profiles on of box-averaged as a function of time...
+i_do_box_TS_z=1 ; # do sigma vert. profiles on given boxes... # 1 => no figures, 2 => figures
+#                 # => needs file FILE_DEF_BOXES !!!
+# => produces time-series f(t,z)
+
+#
+# Deep Mixed volume in prescribed boxes:
+i_do_dmv=1
+export MLD_CRIT="1000,725,500"
+
+
+# Some nerdy stuffs about the critical depth in prescribed boxes:
+i_do_zcrit=0
+
+
+
+
+
+
+# BETA / TESTING:
+
+# Fresh-water transport associated to sea-ice transport
+#  => must compile cdficeflux.x but depends on more recent CDFTOOLS module...
+i_do_icet=0 ; # treat sea-ice volume transport!
+export TRANSPORT_ICE_SECTION_FILE="${BARAKUDA_ROOT}/data/transportiz_eORCA1_ARCTIC.dat"
+
+
+
+
+i_do_flx=0  ; # surface fluxes diags
+
+
+
+
+i_do_amo=0 ;  # buit a SST time serie usable to build Atlantic Multidecadal Oscilation index
+
+
+i_do_sect=0 ; # do sigma vert. profiles on given boxes...
+VSECT_NM=( "Indian_77p5_E" "Atlantic_21p5_W" )
+VSECT_JI=(      "5,5"          "266,266"     ) ; # X range in C convention
+VSECT_JJ=(    "25,170"          "7,291"      ) ; # Y range in C convention

+ 36 - 0
data/TS_sections.dat

@@ -0,0 +1,36 @@
+# These section are config-independant and are
+# defined with 2 points for which coordinates
+# are given in degrees of longitude and latitude
+#
+# Important: only zonal or meridional sections
+#            are allowed
+#
+# Also the maximum and minimum temperature and salinity must be given!
+#
+# Ex:
+# Name_Zonal_Section       lon1 lat0 lon2 lat0
+# Name_Meridional_Section  lon0 lat1 lon0 lat2
+#
+#
+#  Name           lon1     lat1    lon2   lat2       Tmin Tmax   Smin Smax
+#
+Eq_Pacific        110.       0.    -78.    0.          0.  30.   34.5  35.6
+Pacific_144W     -144.     -80.   -144.   62.          0.  30.   33.2  36.4
+Pacific_173W     -173.     -80.   -173.   90.          0.  30.   33.2  36.4
+#
+Eq_Atlantic       -50.       0.     10.    0.          0.  30.   34.5  36.5
+Atlantic_22W      -22.     -80.    -22.   80.          0.  30.   33.6  36.9
+Atlantic_57N      -62.      57.     24.   57.          0.  15.   33.6  36.9
+#
+Weddell_67S       -30.     -67.     11.  -67.         -2.   2.   33.5  35.
+Weddell_37W       -37.     -89.    -37.  -60.         -2.   2.   33.5  35.
+#                               
+Indian_77E         77.     -72.     77.   10.          0.  30.   34.2  35.8
+#                               
+MedSea_19E         19.      30.     19.   45.          12. 24.   36.   40.
+#                               
+Gibraltar_36N     -30.      35.9     0.  35.9          0.  21.   34.5  38.5
+#
+Drake_58S        -140.     -58.      2.  -58.         -1.   7.   33.8  34.8
+#
+EOF

BIN
data/basin_mask_ORCA025_ece3.2_2017.nc4


BIN
data/basin_mask_ORCA1_ece2.2_cmip5.nc4


BIN
data/basin_mask_ORCA1_ece3.2_2017.nc4


+ 4 - 0
data/def_boxes_NASST_ORCA1.txt

@@ -0,0 +1,4 @@
+# Name     i1 ,  j1,  i2, j2  ORCA1
+########################################
+NASST     213 147 296 241
+EOF

+ 5 - 0
data/def_boxes_convection_ORCA025_y1050.txt

@@ -0,0 +1,5 @@
+# Name     i1, j1,  i2, j2
+##############################
+Labrador  936 784  977 847
+GIN      1073 871 1151 955
+EOF

+ 14 - 0
data/def_boxes_convection_ORCA1.txt

@@ -0,0 +1,14 @@
+# Name     i1, j1,  i2, j2
+##############################
+Labrador_old  236  222 252 235
+Labrador  230  230 244 249
+GIN       266 245  290 271
+GIN2      274 251  282 260
+Ice_Scot  255 225  282 243
+Nansen1   272 276  294 291
+Nansen2    67 273   89 289
+Weddel    231  15  265  43
+WedMaud   274  42  297  57
+WedExtr   257  37  276  46
+Amery       6  50   15  60
+EOF

+ 11 - 0
data/def_boxes_convection_ORCA1_ece2.txt

@@ -0,0 +1,11 @@
+# Name     i1, j1,  i2, j2
+##############################
+Labrador  236  222 252 235
+GIN       266 245  290 271
+GIN2      274 251  282 260
+Ice_Scot  255 225  282 243
+Nansen1   272 276  294 291
+Nansen2    67 273   89 289
+Weddell   262  33  317  64
+Davis       2  44   20  64
+EOF

+ 5 - 0
data/def_boxes_convection_ORCA2.txt

@@ -0,0 +1,5 @@
+# Name     i1 ,  j1,  i2, j2
+##############################
+Labrador  115 119 119 123
+Ross       63  10  76  24
+EOF

+ 9 - 0
data/dens_section_ORCA025_y1050.dat

@@ -0,0 +1,9 @@
+DENMARK_STRAIT
+1031 1052 860 860
+FRAM_STRAIT
+1067 1108 972 972
+GIBRALTAR_STRAIT
+1127 1127 680 685
+FAROE_BANK_CHANNEL
+1104 1104 826 838
+EOF

+ 9 - 0
data/dens_section_ORCA1.dat

@@ -0,0 +1,9 @@
+DENMARK_STRAIT
+254 265 245 245
+FAROE_BANK_CHANNEL
+279 279 239 234
+FRAM_STRAIT
+266 282 269 269
+GIBRALTAR_STRAIT
+283 283 202 198
+EOF

+ 15 - 0
data/dens_section_ORCA1_EXTRA.dat

@@ -0,0 +1,15 @@
+DENMARK_STRAIT
+254 265 245 245
+FAROE_BANK_CHANNEL
+279 279 234 239
+FRAM_STRAIT
+266 282 269 269
+GREENLAND-NORWAY_60
+247 290 237 237
+GREENLAND-NORWAY_70
+260 293 256 256
+CANADA-GREENLAND_60
+228 246 236 236
+CANADA-SCOTLAND_56
+230 281 230 230
+EOF

+ 7 - 0
data/dens_section_ORCA2.dat

@@ -0,0 +1,7 @@
+DENMARK_STRAIT
+125 131 123 123
+FAROE_BANK_CHANNEL
+137 137 119 121
+FRAM_STRAIT
+133 139 137 137
+EOF

+ 27 - 0
data/ice_march_north.dat

@@ -0,0 +1,27 @@
+# raw Area March Arctic (10^6 km2)  raw sept. Area Sept Arctic (10^6 km2)
+1979 13.13 14.32  4.53 5.72
+1980 12.92 14.11  4.83 6.02
+1981 12.62 13.81  4.38 5.57
+1982 12.99 14.18  4.38 5.57
+1983 12.84 14.03  4.64 5.83
+1984 12.48 13.67  4.05 5.24
+1985 12.66 13.85  4.17 5.36
+1986 12.65 13.84  4.66 5.85
+1987 12.75 13.94  5.6 5.91
+1988 13.84 14.15  5.31 5.62
+1989 13.14 13.45  4.81 5.12
+1990 13.44 13.75  4.5 4.81
+1991 13.35 13.66  4.46 4.77
+1992 13.41 13.72  5.37 5.68
+1993 13.71 14.02  4.52 4.83
+1994 13.47 13.78  5.08 5.39
+1995 13.27 13.58  4.38 4.69
+1996 12.83 13.14  5.58 5.89
+1997 13.24 13.55  4.84 5.15
+1998 13.5 13.81  4.24 4.55
+1999 13.47 13.78  4.22 4.53
+2000 13.1 13.41  4.31 4.62
+2001 13.57 13.88  4.55 4.86
+2002 13.36 13.67  3.98 4.29
+2003 13.26 13.57  4.01 4.32
+2004 12.93 13.24  4.35 4.66

BIN
data/obs/radsw_monthly_clim_1980-2005_NOCS2.nc4


+ 15 - 0
data/transport_ice_ORCA025_y1050.dat

@@ -0,0 +1,15 @@
+BEIRING-STRAIT
+461 454 863 865
+FRAM-STRAIT
+1107 1067  972 972
+DENMARK-STRAIT
+1045 1055 878 862
+BARENTS-OPENING
+1178 1129 935 956
+CANADA-ARCH-75N
+967 927 963 949
+CANADA-ARCH-66N
+963 937 879 885
+BAFFIN-MOUTH
+908 906 839 855
+EOF

+ 15 - 0
data/transport_ice_ORCA1.dat

@@ -0,0 +1,15 @@
+BEIRING-STRAIT
+117 114 246 246
+FRAM-STRAIT
+279 268 272 272
+BARENTS-OPENING
+296 282 263 270
+DENMARK-STRAIT
+265 261 245 249
+CANADA-ARCH-75N
+243 232 271 271
+CANADA-ARCH-66N
+242 234 251 251
+BAFFIN-MOUTH
+228 226 238 245
+EOF

+ 25 - 0
data/transportiz_EE3.ORCA1.dat

@@ -0,0 +1,25 @@
+DRAKE-PASSAGE
+222 230  66  49
+AUSTRALIA-ANTARCTICA
+ 72  72  91  40
+FLORIDA-STRAIT
+208 208 189 185
+BEIRING-STRAIT
+114 117 246 246
+DENMARK-STRAIT
+261 265 249 245
+ICELAND-FAROE
+271 279 242 239
+FAROE-NORWAY
+279 289 239 239
+ICELAND-NORWAY
+271 289 242 241
+BAFFIN-STRAIT
+234 241 251 248
+FRAM-STRAIT
+268 278 272 272
+SVALBARD-NORWAY
+282 294 269 261
+FAROE-SCOTLAND
+279 281 239 233
+EOF

+ 9 - 0
data/transportiz_ORCA025.dat

@@ -0,0 +1,9 @@
+DRAKE-PASSAGE
+875 920 235 169
+DENMARK-STRAIT
+1016 1055 833 833
+FAROES-BANK-CHANNEL
+1111 1111 780 808
+GIBRALTAR
+1127 1127 652 655
+EOF

+ 23 - 0
data/transportiz_ORCA025_y1050.dat

@@ -0,0 +1,23 @@
+DRAKE-PASSAGE
+912 872 191 261
+AUSTRALIA-ANTARCTICA
+279 279 155 363
+CUBA-FLORIDA
+828 828 621 632
+BEIRING-STRAIT
+461 454 863 865
+FRAM-STRAIT
+1107 1067  972 972
+DENMARK-STRAIT
+1055 1045 862 878
+BARENTS-OPENING
+1178 1129 935 956
+GIBRALTAR-STRAIT
+1127 1127 680 685
+CANADA-ARCH-75N
+967 927 963 949
+CANADA-ARCH-66N
+963 937 879 885
+BAFFIN-MOUTH
+908 906 839 855
+EOF

+ 25 - 0
data/transportiz_ORCA1.dat

@@ -0,0 +1,25 @@
+DRAKE-PASSAGE
+233 221 50 66
+AUSTRALIA-ANTARCTICA
+ 72  72  40  91
+CUBA-FLORIDA
+208 208 185 189
+ref_temp_sali: 15.0 35.0
+BEIRING-STRAIT
+117 114 246 246
+FRAM-STRAIT
+279 268 272 272
+BARENTS-OPENING
+296 282 263 270
+DENMARK-STRAIT
+265 261 245 249
+GIBRALTAR-STRAIT
+283 283 198 202
+ref_temp_sali: 15.0 36.0
+CANADA-ARCH-75N
+243 232 271 271
+CANADA-ARCH-66N
+242 234 251 251
+BAFFIN-MOUTH
+228 226 238 245
+EOF

+ 35 - 0
data/transportiz_ORCA1_ARCTIC.dat

@@ -0,0 +1,35 @@
+SVALBARD-KANIN
+282 308 269 269
+ATLANTIC-70
+230 293 256 256
+GREENLAND-NORWAY-70
+260 293 256 256
+BEIRING-STRAIT
+112 118 246 246
+DENMARK-STRAIT
+261 265 249 245
+ICELAND-FAROE
+271 279 242 239
+FAROE-NORWAY
+279 289 239 239
+ICELAND-NORWAY
+271 289 242 241
+BAFFIN-STRAIT
+234 241 251 248
+FRAM-STRAIT
+268 278 272 272
+FAROE-SCOTLAND
+279 281 239 233
+CANADIAN-ARCHIP
+229 246 272 272
+SVALBARD-NORWAY
+282 294 269 261
+SVALBARD-FRANZJ1
+282 286 275 283
+FRANZJ1-FRANZJ2
+286 287 283 288
+FRANZJ2-NEWZAMB
+287 296 288 289
+NEWZAMB-SIBERIA
+307 312 278 278
+EOF

+ 25 - 0
data/transportiz_ORCA1_COMPLETE.dat

@@ -0,0 +1,25 @@
+DRAKE-PASSAGE
+222 230  66  49
+AUSTRALIA-ANTARCTICA
+ 72  72  91  40
+FLORIDA-STRAIT
+208 208 189 185
+BEIRING-STRAIT
+114 117 246 246
+DENMARK-STRAIT
+261 265 249 245
+ICELAND-FAROE
+271 279 242 239
+FAROE-NORWAY
+279 289 239 239
+ICELAND-NORWAY
+271 289 242 241
+BAFFIN-STRAIT
+234 241 251 248
+FRAM-STRAIT
+268 278 272 272
+SVALBARD-NORWAY
+282 294 269 261
+FAROE-SCOTLAND
+279 281 239 233
+EOF

+ 5 - 0
data/transportiz_ORCA1_FRAM+DS.dat

@@ -0,0 +1,5 @@
+DENMARK-STRAIT
+261 265 249 245
+FRAM-STRAIT
+268 278 272 272
+EOF

+ 11 - 0
data/transportiz_ORCA1_barents.dat

@@ -0,0 +1,11 @@
+SVALBARD-NORWAY
+282 294 269 261
+SVALBARD-FRANZJ1
+282 286 275 283
+FRANZJ1-FRANZJ2
+286 287 283 288
+FRANZJ2-NEWZAMB
+287 296 288 289
+NEWZAMB-SIBERIA
+307 312 278 278
+EOF

+ 47 - 0
data/transportiz_ORCA1_cmip5.dat

@@ -0,0 +1,47 @@
+DRAKE-PASSAGE
+222 230  66  49
+AUSTRALIA-ANTARCTICA
+ 72  72  91  40
+FLORIDA-STRAIT
+208 208 189 185
+BEIRING-STRAIT
+114 117 246 246
+LBRDR-S1
+237 253 223 223
+ref_temp
+3.19
+LBRDR-S2
+253 253 223 236
+ref_temp
+3.19
+LBRDR-S3
+237 253 236 236
+ref_temp
+3.19
+LBRDR-S4
+237 237 223 236
+ref_temp
+3.19
+LBRDR-S3-EAST
+247 253 236 236
+ref_temp
+3.19
+LBRDR-S3-WEST
+237 246 236 236
+ref_temp
+3.19
+GREENLAND-NORWAY-60
+247 290 237 237
+DENMARK-STRAIT
+261 265 249 245
+DENMARK-STRAIT
+261 265 249 245
+FRAM-STRAIT
+268 278 272 272
+BAFFIN-STRAIT
+234 241 251 248
+CANADIAN-ARCHIP
+229 246 272 272
+SVALBARD-NORWAY
+282 294 269 261
+EOF

+ 33 - 0
data/transportiz_ORCA1_extra-ARCTIC.dat

@@ -0,0 +1,33 @@
+DENMARK-STRAIT
+261 265 249 245
+BAFFIN-STRAIT
+234 241 251 248
+FRAM-STRAIT
+268 278 272 272
+SVALBARD-KANIN
+282 308 269 269
+ATLANTIC-70
+230 293 256 256
+GREENLAND-NORWAY-70
+260 293 256 256
+ICELAND-NORWAY
+271 289 242 241
+ICELAND-FAROE
+271 279 242 239
+FAROE-NORWAY
+279 289 239 239
+FAROE-SCOTLAND
+279 281 239 233
+CANADIAN-ARCHIP
+229 246 272 272
+SVALBARD-NORWAY
+282 294 269 261
+SVALBARD-FRANZJ1
+282 286 275 283
+FRANZJ1-FRANZJ2
+286 287 283 288
+FRANZJ2-NEWZAMB
+287 296 288 289
+NEWZAMB-SIBERIA
+307 312 278 278
+EOF

+ 25 - 0
data/transportiz_ORCA1_extra-LS_square.dat

@@ -0,0 +1,25 @@
+LBRDR-S1
+237 253 223 223
+ref_temp
+3.185
+LBRDR-S2
+253 253 223 236
+ref_temp
+3.185
+LBRDR-S3
+237 253 236 236
+ref_temp
+3.185
+LBRDR-S4
+237 237 223 236
+ref_temp
+3.185
+LBRDR-S3-EAST
+247 253 236 236
+ref_temp
+3.185
+LBRDR-S3-WEST
+237 246 236 236
+ref_temp
+3.185
+EOF

+ 17 - 0
data/transportiz_ORCA1_extra_NAtl.dat

@@ -0,0 +1,17 @@
+DRAKE-PASSAGE
+222 230  66  49
+AUSTRALIA-ANTARCTICA
+ 72  72  91  40
+FLORIDA-STRAIT
+208 208 189 185
+BEIRING-STRAIT
+114 117 246 246
+GREENLAND-IRELAND
+247 278 236 223
+CANADA-BRETAGNE
+233 284 226 218
+GREENLAND-NORWAY-60
+247 290 237 237
+LABRADOR-GATE
+233 246 226 236
+EOF

+ 11 - 0
data/transportiz_ORCA1_light.dat

@@ -0,0 +1,11 @@
+DRAKE-PASSAGE
+222 230  66  49
+FLORIDA-STRAIT
+208 208 189 185
+BEIRING-STRAIT
+114 117 246 246
+DENMARK-STRAIT
+261 265 249 245
+FRAM-STRAIT
+268 278 272 272
+EOF

+ 9 - 0
data/transportiz_ORCA1_minimum.dat

@@ -0,0 +1,9 @@
+DRAKE-PASSAGE
+222 230  66  49
+AUSTRALIA-ANTARCTICA
+ 72  72  91  40
+FLORIDA-STRAIT
+208 208 189 185
+BEIRING-STRAIT
+114 117 246 246
+EOF

+ 15 - 0
data/transportiz_ORCA1_old.dat

@@ -0,0 +1,15 @@
+DRAKE-PASSAGE
+221 230  66  49
+AUSTRALIA-ANTARCTICA
+ 72  72  91  40
+FLORIDA-STRAIT
+208 208 189 185
+BEIRING-STRAIT
+114 117 246 246
+DENMARK-STRAIT
+261 265 249 245
+GREENLAND-NORWAY-60
+247 290 237 237
+GIBRALTAR-STRAIT
+283 283 201 199
+EOF

+ 11 - 0
data/transportiz_ORCA2.dat

@@ -0,0 +1,11 @@
+DRAKE-PASSAGE
+109 114 33 25
+AUSTRALIA-ANTARCTICA
+32 31 45 21
+FLORIDA-STRAIT
+101 101 96 93
+BEIRING-STRAIT
+55 58 122 122
+DENMARK-STRAIT
+129 131 126 123
+EOF

+ 29 - 0
data/transportiz_ORCA2_all.dat

@@ -0,0 +1,29 @@
+DRAKE-PASSAGE
+109 114 33 25
+AUSTRALIA-ANTARCTICA
+32 31 45 21
+FLORIDA-STRAIT
+101 101 96 93
+BEIRING-STRAIT
+55 58 122 122
+DENMARK-STRAIT
+129 131 126 123
+ICELAND-FAROE
+1 1 1 1
+FAROE-NORWAY
+1 1 1 1
+ICELAND-NORWAY
+1 1 1 1
+BAFFIN-STRAIT
+113 119 126 126
+FRAM-STRAIT
+129 131 126 122
+SVALBARD-NORWAY
+1 1 1 1
+FAROE-SCOTLAND
+1 1 1 1
+ICELAND-SCOTLAND
+133 138 122 117
+GREENLAND-NORWAY-60
+121 143 119 119
+EOF

+ 36 - 0
platform/cca.job.tmpl

@@ -0,0 +1,36 @@
+#! /usr/bin/env bash
+
+#PBS -N b_<EXPID>_<DIAG>
+#PBS -q nf
+#PBS -l EC_billing_account=<ACCOUNT>
+#PBS -l EC_total_tasks=1
+#PBS -l EC_threads_per_task=12
+#PBS -l EC_hyperthreads=1
+#PBS -l walltime=05:00:00
+#PBS -j oe
+#PBS -o <OUT>/log/barakuda_<EXPID>_<DIAG>.out
+
+##PBS -l EC_memory_per_task=24GB
+
+# -------- CONFIG
+module unload PrgEnv-cray
+module unload PrgEnv-intel
+module unload PrgEnv-gnu
+module unload python
+
+module load PrgEnv-intel
+
+module load cray-snplauncher
+module load nco netcdf
+
+module load python/2.7.12-01
+
+set -e
+
+mkdir <OUT>/log || true
+
+cd <BARAKUDA_TOPDIR>
+ 
+export OMP_NUM_THREADS=$EC_threads_per_task
+
+mpiexec -n 1 <CMD>

+ 174 - 0
platform/meta_launch_cca.sh

@@ -0,0 +1,174 @@
+#!/bin/bash -e
+
+#---------------------------------------------------------------------------
+# With PBSpro (qsub) you cannot pass arguments to a script at the command line,
+#  like this: 
+#
+#     qsub <qsub_options> script arg1 arg2
+#
+# Only this is posiible:
+#
+#     qsub <qsub_options> script
+#
+# So we rely on a template, which is parsed here to create a script that can
+#  be submitted and has all the options we want.
+#
+#---------------------------------------------------------------------------
+# HOW-TO
+#     you have to first "cd <location of barakuda package>/platform" and
+#     then:
+#
+#       ./meta_launch_cca.sh -C ......
+#
+#---------------------------------------------------------------------------
+# OPTIONAL SETTING
+#
+#   - you can overwrite the default hpc account for running barakuda with (in
+#     your ~/.user_bashrc or ~/.bashrc):
+#   
+#       export ECE3_POSTPROC_ACCOUNT=<hpc account to use>
+#
+#     If not set, your default ECMWF account is used (i.e. 1st one in the list
+#     you get with "account -l $USER" on ecgate). Note that you can also
+#     specify an account at the command line when calling the script with the
+#     -a option.
+#
+#---------------------------------------------------------------------------
+#    P. Le Sager, June/July 2017
+#---------------------------------------------------------------------------
+
+usage() {
+    echo
+    echo "USAGE: ${0} -C <config> -R <experiment>  (options)"
+    echo
+    echo "     Available configs are:"
+    for cc in ${list_conf}; do
+        echo "         * ${cc}"
+    done
+    echo
+    echo "Options are:"
+    echo
+    echo "   -a ACCOUNT    : specify a different special project for accounting (default: \$ECE3_POSTPROC_ACCOUNT)"
+    echo "   -i YEAR_START : first year to build climatolgy. Climatology is built if set."
+    echo "   -e YEAR_END   :  last year to build climatolgy. Climatology is built if set."
+    echo
+    exit
+}
+
+# -------- Checks before submitting
+[[ -z $ECE3_BARAKUDA_TOPDIR ]] && cd .. && ECE3_BARAKUDA_TOPDIR=$PWD
+cd $ECE3_BARAKUDA_TOPDIR
+
+# Available configs:
+list_conf=$(\ls ${ECE3_BARAKUDA_TOPDIR}/configs/config_*.sh | sed -e "s|${ECE3_BARAKUDA_TOPDIR}/configs\/config_||g" -e s/'.sh'/''/g)
+
+# User configs, potentially in the directory from which barakuda.sh is called:
+list_conf+=" $(\ls ./config_*.sh 2>/dev/null | sed -e "s|.\/config_||g" -e s/'.sh'/''/g)"
+
+# -------- Options
+account=$ECE3_POSTPROC_ACCOUNT  # default account if exists
+climato=0
+
+while getopts C:R:a:i:e: option ; do
+    case $option in
+        C) conf=${OPTARG} ;;
+        R) exp=${OPTARG} ;;
+        a) account=$OPTARG ;;
+        i) y1=${OPTARG} ;;
+        e) y2=${OPTARG} ;;
+        *) usage ;;
+    esac
+done
+shift $((OPTIND-1))
+
+[[ -n $y1 &&  -n $y2 ]] && climato=1 # generate climato, and compare with it
+
+[[ -z $conf ]] && usage
+[[ ! ${list_conf} =~ ${conf} ]] && { echo ; echo "!!!! UNKNOWN CONF: $conf !!!!!"; usage;}
+[[ -z $exp ]] && usage
+
+
+# -- Scratch dir (location of submit script and its log)
+
+OUT=$SCRATCH/tmp_barakuda
+mkdir -p $OUT
+
+
+# -------- Create diagnostics
+
+cmd="./barakuda.sh -C ${conf} -R ${exp}"
+
+tgt_script=$OUT/b_${exp}_diag.job
+
+sed "s/<EXPID>/$exp/" < platform/cca.job.tmpl > $tgt_script
+
+[[ -n $account ]] && \
+    sed -i "s/<ACCOUNT>/$account/" $tgt_script || \
+    sed -i "/<ACCOUNT>/ d" $tgt_script
+
+sed -i "s|<BARAKUDA_TOPDIR>|${ECE3_BARAKUDA_TOPDIR}|"  $tgt_script
+sed -i "s|<DIAG>|diag|"  $tgt_script
+sed -i "s|<OUT>|$OUT|"   $tgt_script
+sed -i "s|<CMD>|${cmd}|" $tgt_script
+
+diagid=$(qsub $tgt_script)
+echo $diagid
+
+
+# -------- Create climatologies
+
+if (( $climato ))
+then
+    cmd="./build_clim.sh -C ${conf} -R ${exp} -i $y1 -e $y2"
+    
+    tgt_script=$OUT/b_${exp}_climato.job
+    
+    sed "s/<EXPID>/$exp/" < platform/cca.job.tmpl > $tgt_script
+    
+    [[ -n $account ]] && \
+        sed -i "s/<ACCOUNT>/$account/" $tgt_script || \
+        sed -i "/<ACCOUNT>/ d" $tgt_script
+    
+    sed -i "s|<BARAKUDA_TOPDIR>|${ECE3_BARAKUDA_TOPDIR}|"  $tgt_script
+    sed -i "s|<DIAG>|clim|"  $tgt_script
+    sed -i "s|<OUT>|$OUT|"   $tgt_script
+    sed -i "s|<CMD>|${cmd}|" $tgt_script
+    
+    climid=$(qsub $tgt_script)
+    echo $climid
+fi
+
+
+# -------- Create figures
+
+if (( $climato ))
+then
+    cmd="./barakuda.sh -C ${conf} -R ${exp} -E"
+else
+    cmd="./barakuda.sh -C ${conf} -R ${exp} -e"
+fi
+
+tgt_script=$OUT/b_${exp}_fig.job
+
+sed "s/<EXPID>/$exp/" < platform/cca.job.tmpl > $tgt_script
+
+[[ -n $account ]] && \
+    sed -i "s/<ACCOUNT>/$account/" $tgt_script || \
+    sed -i "/<ACCOUNT>/ d" $tgt_script
+
+sed -i "s|<BARAKUDA_TOPDIR>|${ECE3_BARAKUDA_TOPDIR}|"  $tgt_script
+sed -i "s|<DIAG>|fig|"  $tgt_script
+sed -i "s|<OUT>|$OUT|"   $tgt_script
+sed -i "s|<CMD>|${cmd}|" $tgt_script
+
+if (( $climato ))
+then
+    qsub -W depend=afterok:$diagid:$climid  $tgt_script
+else
+    qsub -W depend=afterok:$diagid  $tgt_script
+fi
+
+
+# --------- info
+
+qstat -wu $USER

+ 29 - 0
platform/meta_launch_nsc.sh

@@ -0,0 +1,29 @@
+#!/bin/bash -ue
+#
+# K. Wyser, July 2016
+#
+
+while getopts C:R:i:e: option ; do
+    case $option in
+        C) conf=${OPTARG} ;;
+        R) expname=${OPTARG} ;;
+        i) y1=${OPTARG} ;;
+        e) y2=${OPTARG} ;;
+    esac
+done
+
+job_name=b-$expname
+
+launch_cmd='sbatch -A snic2014-10-1 --reservation=dcs -n 1 -t 4:0:0'
+
+ll=$( $launch_cmd -J $job_name-1 barakuda.sh -C $conf -R $expname )
+echo $ll
+job1_id=$(echo $ll | awk '{print $4}')
+
+ll=$( $launch_cmd -J $job_name-2 build_clim.sh -C $conf -R $expname -i $y1 -e $y2)
+echo $ll
+job2_id=$(echo $ll | awk '{print $4}')
+
+$launch_cmd -d afterok:$job1_id:$job2_id -J $job_name-3 barakuda.sh -C $conf -R $expname -E
+
+exit 0

+ 78 - 0
platform/meta_launch_rhino.sh

@@ -0,0 +1,78 @@
+#!/bin/bash
+#
+# based on NSC script of K. Wyser, July 2016
+#
+
+set -ex
+
+usage() {
+    echo
+    echo "USAGE: ${0} -C <config> -R <experiment>  (options)"
+    echo
+    echo "     Available configs are:"
+    for cc in ${list_conf}; do
+        echo "         * ${cc}"
+    done
+    echo
+    echo "Options are:"
+    echo
+    echo "   -i YEAR_START : first year to build climatolgy. Climatology is built if set."
+    echo "   -e YEAR_END   :  last year to build climatolgy. Climatology is built if set."
+    echo
+    exit
+}
+
+climato=0
+while getopts C:R:i:e: option ; do
+    case $option in
+        C) conf=${OPTARG} ;;
+        R) expname=${OPTARG} ;;
+        i) y1=${OPTARG} ;;
+        e) y2=${OPTARG} ;;
+        *) usage ;;
+    esac
+done
+shift $((OPTIND-1))
+
+[[ -n $y1 &&  -n $y2 ]] && climato=1 # generate climato, and compare with it
+
+# -------- Checks before submitting
+cd ..
+
+# Available configs
+list_conf=$(\ls ./configs/config_*.sh | sed -e "s|./configs\/config_||g" -e s/'.sh'/''/g)
+
+# User configs, potentially in the directory from which barakuda.sh is called
+list_conf+=" $(\ls ./config_*.sh 2>/dev/null | sed -e "s|.\/config_||g" -e s/'.sh'/''/g)"
+
+[[ -z $conf ]] && usage
+[[ -z $expname ]] && usage
+
+
+job_name=b-$expname
+launch_cmd='sbatch -n 1 -c 12'
+
+# -------- Create diagnostics
+
+ll=$( $launch_cmd -J $job_name-1 barakuda.sh -C $conf -R $expname )
+echo $ll
+job1_id=$(echo $ll | awk '{print $4}')
+
+# -------- Create climatologies
+
+if (( $climato ))
+then
+    ll=$( $launch_cmd -J $job_name-2 build_clim.sh -C $conf -R $expname -i $y1 -e $y2)
+    echo $ll
+    job2_id=$(echo $ll | awk '{print $4}')
+fi
+
+# -------- Create figures
+
+if (( $climato ))
+then
+    $launch_cmd -d afterok:$job1_id:$job2_id -J $job_name-3 barakuda.sh -C $conf -R $expname -E
+else
+    $launch_cmd -d afterok:$job1_id -J $job_name-3 barakuda.sh -C $conf -R $expname -e
+fi
+

+ 111 - 0
python/exec/.old/orca025_create_basin_mask_from_meshmask.py

@@ -0,0 +1,111 @@
+#!/usr/bin/env python
+
+# Petteri Uotila, 2015
+
+import sys
+import numpy as nmp
+from netCDF4 import Dataset
+from string import replace
+
+if len(sys.argv) != 2:
+    print 'Usage: '+sys.argv[0]+' <mesh_mask_ORCA025_file.nc>'
+    sys.exit(0)
+
+cf_mm  = sys.argv[1]
+cf_out = replace(cf_mm, 'mesh_mask', 'basin_mask')
+
+
+print '\n'
+
+# Opening the Netcdf file:
+f_mm = Dataset(cf_mm)
+print 'File ', cf_mm, 'is open...\n'
+
+# Extracting the longitude 2D array:
+xlon = f_mm.variables['nav_lon'][:,:]
+
+# Extracting the longitude 2D array:
+xlat = f_mm.variables['nav_lat'][:,:]
+
+# Extracting tmask at surface level:
+tmask  = f_mm.variables['tmask'][0,0,:,:]
+
+f_mm.close()
+
+
+
+# Info on the shape of t:
+[ nj, ni ] = tmask.shape
+
+print 'Dimension = ', ni, nj, '\n'
+
+mask_atl = nmp.zeros((nj,ni))
+mask_pac = nmp.zeros((nj,ni))
+mask_ind = nmp.zeros((nj,ni))
+mask_soc = nmp.zeros((nj,ni))
+
+f_mo025 = Dataset('new_maskglo_ORCA025.nc')
+# ATL for ORCA025
+# ~~~~~~~~~~~~~
+mask_atl[:,:] = f_mo025.variables['tmaskatl'][:]
+mask_atl[835:,:] = tmask[835:,:]
+
+# PAC for ORCA1
+# ~~~~~~~~~~~~~
+mask_pac[:,:] = f_mo025.variables['tmaskpac'][:]
+mask_pac[:357,:] = 0
+mask_pac[355:376,225:266] = 0 # mask the Great Australian Bight
+
+# IND for ORCA1
+# ~~~~~~~~~~~~~
+mask_ind[:,:] = f_mo025.variables['tmaskind'][:]
+
+# Indo-Pacific
+# ~~~~~~~~~~~~
+idx = nmp.where((mask_pac==1)|(mask_ind==1))
+mask_inp[idx] = 1
+
+# Southern Ocean
+mask_soc[:,:] = f_mo025.variables['tmaskant'][:]
+mask_soc[255:357,:] = tmask[255:357,:]
+
+f_mo025.close()
+
+# Creating output file:
+f_out = Dataset(cf_out, 'w',format='NETCDF3_CLASSIC')
+
+# Dimensions:
+f_out.createDimension('x', ni)
+f_out.createDimension('y', nj)
+
+# Variables
+id_lon  = f_out.createVariable('nav_lon','f4',('y','x',))
+id_lat  = f_out.createVariable('nav_lat','f4',('y','x',))
+
+id_atl  = f_out.createVariable('tmaskatl' ,'f4',('y','x',)) ; id_atl.long_name = 'Atlantic Basin'
+id_pac  = f_out.createVariable('tmaskpac' ,'f4',('y','x',)) ; id_pac.long_name = 'Pacific Basin'
+id_ind  = f_out.createVariable('tmaskind' ,'f4',('y','x',)) ; id_ind.long_name = 'Indian Basin'
+id_soc  = f_out.createVariable('tmasksoc' ,'f4',('y','x',)) ; id_soc.long_name = 'Southern Basin'
+id_inp  = f_out.createVariable('tmaskinp' ,'f4',('y','x',)) ;  id_inp.long_name = 'Indo-Pacific Basin'
+
+
+# Filling variables:
+id_lat[:,:]    =   xlat[:,:]
+id_lon[:,:]    =   xlon[:,:]
+
+id_atl[:,:]  =  mask_atl[:,:]
+id_pac[:,:]  =  mask_pac[:,:]
+id_ind[:,:]  =  mask_ind[:,:]
+id_soc[:,:]  =  mask_soc[:,:]
+
+id_inp[:,:]  =  mask_inp[:,:]
+
+
+f_out.About  = 'ORCA1 main oceanic basin land-sea mask created from '+cf_mm
+f_out.Author = ' Generated with "orca025_create_basin_mask_from_meshmask.py" of BaraKuda (https://github.com/brodeau/barakuda)'
+
+f_out.close()
+
+
+print cf_out+' sucessfully created!'
+

+ 215 - 0
python/exec/.old/orca1_create_basin_mask_from_meshmask.py

@@ -0,0 +1,215 @@
+#!/usr/bin/env python
+
+# L. Brodeau, april 2010
+
+import sys
+import numpy as nmp
+from netCDF4 import Dataset
+from string import replace
+
+if len(sys.argv) != 2:
+    print 'Usage: '+sys.argv[0]+' <mesh_mask_ORCA1_file.nc>'
+    sys.exit(0)
+
+cf_mm  = sys.argv[1]
+cf_out = replace(cf_mm, 'mesh_mask', 'basin_mask')
+
+
+print '\n'
+
+# Opening the Netcdf file:
+f_mm = Dataset(cf_mm)
+print 'File ', cf_mm, 'is open...\n'
+
+# Extracting the longitude 2D array:
+xlon = f_mm.variables['nav_lon'][:,:]
+
+# Extracting the longitude 2D array:
+xlat = f_mm.variables['nav_lat'][:,:]
+
+# Extracting tmask at surface level:
+tmask  = f_mm.variables['tmask'][0,0,:,:]
+
+f_mm.close()
+
+
+
+# Info on the shape of t:
+[ nj, ni ] = tmask.shape
+
+print 'Dimension = ', ni, nj, '\n'
+
+mask_atl = nmp.zeros((nj,ni))
+mask_pac = nmp.zeros((nj,ni))
+mask_ind = nmp.zeros((nj,ni))
+mask_soc = nmp.zeros((nj,ni)) ; # Souther Ocean
+mask_wed = nmp.zeros((nj,ni)) ; # Weddell Sea
+
+mask_ip1 = nmp.zeros((nj,ni))
+mask_inp = nmp.zeros((nj,ni))
+
+
+
+
+# ATL for ORCA1
+# ~~~~~~~~~~~~~
+mask_atl[:,:] = tmask[:,:]
+
+# Removing Southern Ocean:
+#mask_atl[:95,:] = 0
+
+# Removing Pacific and Indian
+mask_atl[0:246,0:190] = 0 # 246 => to keep Pacific side of the arctic basin...
+mask_atl[0:168,0:223] = 0 ; mask_atl[0:255,310:] = 0
+mask_atl[165:177,190:204] = 0; mask_atl[165:180,190:198] = 0; mask_atl[165:170,200:206] = 0
+mask_atl[188:209,282:] = 0; mask_atl[209:215,288:] = 0
+
+
+
+# REMOVING INDONESIA + AUSTRALIA
+# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+mask_ip1[:,:] = tmask[:,:]
+
+mask_ip1[114:122,53:75] = 0
+mask_ip1[119:126,68:74] = 0
+mask_ip1[124:143,44:59] = 0
+mask_ip1[128:159,33:42] = 0
+mask_ip1[120:142,52:61] = 0
+mask_ip1[124:136,41:70] = 0
+mask_ip1[127:128,37:42] = 0
+mask_ip1[120:126,60:70] = 0
+mask_ip1[141:158,30:33] = 0
+mask_ip1[152:162,26:30] = 0
+
+
+
+
+
+
+# PAC for ORCA1
+# ~~~~~~~~~~~~~
+mask_pac[:,:] = tmask[:,:]
+
+# Removing Southern Ocean until souther Australia:
+mask_pac[:95,:] = 0
+
+
+# Removing Indonesian side
+mask_pac[:,:45] = 0
+mask_pac[88:145,45:61] = 0
+mask_pac[112:125,59:70] = 0
+mask_pac[123:136,60:67] = 0
+mask_pac[88:99,60:71] = 0 # bottom Australia
+
+
+# V2
+#mask_pac[:,:26] = 0
+
+
+
+# Removing Atlantic
+idxatl = nmp.where(mask_atl == 1.0)
+mask_pac[idxatl] = 0
+
+# Removing atlantic bottom and the rest (Indian)
+mask_pac[83:,224:] = 0
+
+
+# IND for ORCA1
+# ~~~~~~~~~~~~~
+mask_ind[:,:] = tmask[:,:]
+
+# Removing Southern Ocean until southern Australia:
+mask_ind[:95,:] = 0
+
+# Removing Atl and Pac
+mask_ind[:,:] = mask_ind[:,:] - mask_atl[:,:] - mask_pac[:,:]
+
+mask_ind[93:100,46:68] = 0 # australia bottom
+
+# Removing Mediterranean+Caspian sea:
+mask_ind[192:228,279:329] = 0
+mask_ind[198:242,328:344] = 0
+
+
+
+
+
+
+
+# Indo-Pacific
+# ~~~~~~~~~~~~
+mask_inp[:,:] = tmask[:,:]
+mask_inp[:95,:] = 0
+
+# Removing Atlantic
+idxatl = nmp.where(mask_atl == 1.0)
+mask_inp[idxatl] = 0
+
+mask_inp[93:100,46:68] = 0 # australia bottom
+
+# Removing Mediterranean sea:
+mask_inp[192:228,279:329] = 0
+mask_inp[198:242,328:344] = 0
+
+# Removing indonesia
+#mask_inp[:,:] = mask_inp[:,:] * mask_ip1[:,:]
+
+
+
+
+
+# Souther Ocean
+mask_soc[:,:] = tmask[:,:]
+idxatl = nmp.where(mask_atl+mask_pac+mask_ind > 0.5)
+mask_soc[idxatl] = 0
+mask_soc[122:,:] = 0
+
+# Weddell Sea:
+mask_wed[:,:] = tmask[:,:]
+mask_wed[:,:233] = 0
+mask_wed[55:,:]  = 0
+mask_wed[:,300:] = 0
+
+
+
+
+# Creating output file:
+f_out = Dataset(cf_out, 'w',format='NETCDF3_CLASSIC')
+
+# Dimensions:
+f_out.createDimension('x', ni)
+f_out.createDimension('y', nj)
+
+# Variables
+id_lon  = f_out.createVariable('nav_lon','f4',('y','x',))
+id_lat  = f_out.createVariable('nav_lat','f4',('y','x',))
+
+id_atl  = f_out.createVariable('tmaskatl' ,'f4',('y','x',)) ; id_atl.long_name = 'Atlantic Basin'
+id_pac  = f_out.createVariable('tmaskpac' ,'f4',('y','x',)) ; id_pac.long_name = 'Pacific Basin'
+id_ind  = f_out.createVariable('tmaskind' ,'f4',('y','x',)) ; id_ind.long_name = 'Indian Basin'
+id_soc  = f_out.createVariable('tmasksoc' ,'f4',('y','x',)) ; id_soc.long_name = 'Southern Basin'
+id_inp  = f_out.createVariable('tmaskinp' ,'f4',('y','x',)) ;  id_inp.long_name = 'Indo-Pacific Basin'
+id_wed  = f_out.createVariable('tmaskwed' ,'f4',('y','x',)) ; id_wed.long_name  = 'Weddell Sea'
+
+
+# Filling variables:
+id_lat[:,:]    =   xlat[:,:]
+id_lon[:,:]    =   xlon[:,:]
+
+id_atl[:,:]  =  mask_atl[:,:]
+id_pac[:,:]  =  mask_pac[:,:]
+id_ind[:,:]  =  mask_ind[:,:]
+id_soc[:,:]  =  mask_soc[:,:]
+id_inp[:,:]  =  mask_inp[:,:]
+id_wed[:,:]  =  mask_wed[:,:]
+
+
+f_out.About  = 'ORCA1 main oceanic basin land-sea mask created from '+cf_mm
+f_out.Author = ' Generated with "orca1_create_basin_mask_from_meshmask.py" of BaraKuda (https://github.com/brodeau/barakuda)'
+
+f_out.close()
+
+
+print cf_out+' sucessfully created!'
+

Some files were not shown because too many files changed in this diff